Styles
The Avalonia UI style system is a mechanism that can share property settings between controls.
A Style
in Avalonia is more similar to a CSS style than a WPF/UWP style. The equivalent of a WPF/UWP Style in Avalonia is a ControlTheme
.
How It Works
In essence, the styling mechanism has two steps: selection and substitution. The XAML for the style can define how both of these steps are to be done, but often you will help the selection step by defining 'class' labels on control elements.
The Avalonia UI styling system's use of 'class' labels on control elements is analogous to how CSS (cascading style sheets) work with HTML elements.
The styling system implements cascading styles by searching the logical tree upwards from a control, during the selection step. This means styles defined at the highest level of the application (the App.axaml
file) can be used anywhere in an application, but may still be overridden closer to a control (for example in a window, or user control).
When a match is located by the selection step, then the matched control's properties are altered according to the setters in the style.
How it is Written
The XAML for a style has two parts: a selector attribute, and one or more setter elements. The selector value contains a string that uses the Avalonia UI style selector syntax. Each setter element identifies the property that will be changed by name, and the new value that will be substituted. The pattern is like this:
<Style Selector="selector syntax">
<Setter Property="property name" Value="new value"/>
...
</Style>
The Avalonia UI style selector syntax is analogous to that used by CSS (cascading style sheets). For detailed reference information, see here.
Example
This is an example of how a style is written and applied to a control element, with a style class to help selection:
<Window ... >
<Window.Styles>
<Style Selector="TextBlock.h1">
<Setter Property="FontSize" Value="24"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>
</Window.Styles>
<StackPanel Margin="20">
<TextBlock Classes="h1">Heading 1</TextBlock>
</StackPanel>
</Window>
In this example, all TextBlock
elements with the h1
style class will be displayed with the font size and weight set by the style. This works in the preview pane:
Where to put Styles
Styles are placed inside a Styles
collection element on a Control
or on the Application
. For example, a window styles collection looks like this:
<Window.Styles>
<Style> ... </Style>
</Window.Styles>