Синтаксис Селекторов Стилей
На этой странице представлен синтаксис селекторов стилей как для XAML, так и для C#, выполняющих идентичные действия.
По Классу Элемента Управления
<Style Selector="Button">
<Style Selector="local|Button">
new Style(x => x.OfType<Button>());
new Style(x => x.OfType(typeof(Button)));
Находит элемент управления по его имени.
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, see below.
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)
.
By Name
<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
attribute, with an added #
(hash) character prefix.
By Style Class
<Style Selector="Button.large">
<Style Selector="Button.large.red">
new Style(x => x.OfType<Button>().Class("large"));
new Style(x => x.OfType<Button>().Class("large").Class("red"));
Selects a control with the specified style class or classes. Multiple classes are separated with a full stop. If multiple classes are specified in the selector, then the control must have all of the requested classes defined for a match.
By Pseudo Class
<Style Selector="Button:focus">
<Style Selector="Button.large:focus">
new Style(x => x.OfType<Button>().Class(":focus"));
new Style(x => x.OfType<Button>().Class("large").Class(":focus"));
Selects a control using its current pseudo class. The colon character defines the start of the pseudo class name in the selector. There can only be one pseudo class in the selector. When used in combination with other classes, the pseudo class must be the last in the list.
For more detail about pseudo classes, see the reference here.
Include Derived Classes
<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 style class selector except it also matches derived types.
Technical detail: during the matching process, Avalonia UI determines the type of a control by examining its StyleKey
property.
INterestingly, this allows you to write very general class-based selectors. As controls are all derived from the class Control
, a selector that only selects on the style class margin2
can be written:
<Style Selector=":is(Control).margin2">
<Style Selector=":is(local|Control.margin2)">