Skip to main content

Style selectors

Avalonia uses style selectors to match controls using a custom XAML syntax that is similar to CSS (Cascading Style Sheets). Selectors determine which controls a style applies to.

Selector quick reference​

SelectorDescription
ButtonSelects all Button controls.
Button.redSelects all Button controls with the red style class.
Button.red.largeSelects all Button controls with both red and large style classes.
Button:focusSelects all Button controls with the :focus pseudo-class active.
Button.red:focusSelects all Button controls with the red class and :focus pseudo-class.
Button#myButtonSelects the Button with Name="myButton".
StackPanel Button.xlSelects Button.xl controls that are descendants (any depth) of a StackPanel.
StackPanel > Button.xlSelects Button.xl controls that are direct children of a StackPanel.
Button /template/ ContentPresenterSelects a specified control inside a Button control template. (ContentPresenter in this example.)
:is(Button)Selects controls that are Button or derive from Button.
:not(Button.red)Selects controls that do not match Button.red.
Button:nth-child(2n+1)Selects odd-numbered Button controls among their siblings.

How selectors work​

A style selector is specified on the Selector attribute of a Style:

<Style Selector="Button.primary:pointerover">
<Setter Property="Background" Value="DarkBlue" />
</Style>

This selector targets all Button controls with the primary style class when the pointer is hovering over them. Multiple parts compose left to right:

  1. Button matches the control type
  2. .primary matches a style class
  3. :pointerover matches a pseudo-class (state)

Selector specificity​

When multiple styles match the same control, the more specific selector wins. Specificity is determined by (in order of priority):

  1. Name selectors (#name) are most specific
  2. Property and pseudo-class selectors (:pointerover, [IsEnabled=True])
  3. Style class selectors (.primary)
  4. Type selectors (Button)
  5. Descendant/child combinators are resolved by position in the tree

If two selectors have equal specificity, the one declared later wins.

Full reference​

For a complete description of all selector formats, operators, and combinators, see the style selector syntax reference.

See also​