Selectors
OfType
- XAML
- C#
<Style Selector="Button">
<Style Selector="local|Button">
new Style(x => x.OfType<Button>());
new Style(x => x.OfType(typeof(Button)));
Selects a control by type. The first example above selects the Avalonia.Controls.Button
class. To include a XAML namespace in the type separate the namespace and the type with a |
character.
This selector does not match derived types. For that, use the Is
selector.
Note the type of an object is actually determined by looking at its StyleKey
property. By default this simply returns the type of the current instance, but if, for example, you do want your control which inherits from Button
to be styled as a Button
, then you can override the StyleKeyOverride
property on your class to return typeof(Button)
.
Name
- XAML
- C#
<Style Selector="#myButton">
<Style Selector="Button#myButton">
new Style(x => x.Name("myButton"));
new Style(x => x.OfType<Button>().Name("myButton"));
Selects a control by its Name
property with a #
character.
Class
- XAML
- C#
<Style Selector="Button.large">
<Style Selector="Button.large:focus">
new Style(x => x.OfType<Button>().Class("large"));
new Style(x => x.OfType<Button>().Class("large").Class(":focus"));
Selects a control with the specified style classes. Multiple classes should be separated with a .
character, or a :
character in the case of pseudoclasses. If multiple classes are specified then the control must have all of the requested classes present in order to match.
Is
- XAML
- C#
<Style Selector=":is(Button)">
<Style Selector=":is(local|Button)">
new Style(x => x.Is<Button>());
new Style(x => x.Is(typeof(Button)));
This is very similar to the OfType
selector except it also matches derived types.
Again, the type of an object is actually determined by looking at its IStyleable.StyleKey
property.
Child
- XAML
- C#
<Style Selector="StackPanel > Button">
new Style(x => x.OfType<StackPanel>().Child().OfType<Button>());
A child selector is defined by separating two selectors with a >
character. This selector matches direct children in the logical tree, so in the example above the selector will match any Button
that is a direct logical child of a StackPanel
.
Descendant
- XAML
- C#
<Style Selector="StackPanel Button">
new Style(x => x.OfType<StackPanel>().Descendant().OfType<Button>());
When two selectors are separated by a space, then the selector will match descendants in the logical tree, so in this case the selector will match any Button
that is a logical descendant of a StackPanel
.
PropertyEquals
- XAML
- C#
<Style Selector="Button[IsDefault=true]">
new Style(x => x.OfType<Button>().PropertyEquals(Button.IsDefaultProperty, true));
Matches any control which has the specified property set to the specified value.
Note: When using a AttachedProperty
in selectors inside XAML, it has to be wrapped in parenthesis.
<Style Selector="TextBlock[(Grid.Row)=0]">
Note: When using in selectors in XAML, properties must support TypeConverter