Search code examples
avaloniaui

How do I use a style selector to select custom controls in Avalonia?


I want to make a Play-Pause Toggle Button in Avalonia with Material.Icon.Avalonia packge.

My approach is to use the style selector to change the MaterialIcon's Kind property based on the Togglebutton's IsChecked property, but it doesn't work.

Here is my code:

xmlns:materialIcons="clr-namespace:Material.Icons.Avalonia;assembly=Material.Icons.Avalonia"
<ToggleButton Width="40"
              Height="40"
              Command="{Binding PlayOrPauseVideoCommand}"
              IsChecked="{Binding IsPlaying}">
    <ToggleButton.Styles>
        <Style x:SetterTargetType="{x:Type materialIcons:MaterialIcon}"
               Selector="ToggleButton:checked materialIcons:MaterialIcon">
            <Setter Property="Kind" Value="Pause" />
        </Style>
    </ToggleButton.Styles>
    <Grid>
        <materialIcons:MaterialIcon x:Name="PlayorPauseIcon"
                                    Width="30"
                                    Height="30"
                                    Kind="Play" />
    </Grid>
</ToggleButton>

There is tow problems.

  1. If I use Selector="ToggleButton:checked materialIcons:MaterialIcon" instead of Selector="ToggleButton:checked #PlayorPauseIcon".
    Avalonia error AVLN:0004: Unable to resolve type materialIcons from namespace https://github.com/avaloniaui will be occured during build the project.
    Is there an another way to select a custom control instand of naming it and use Selector="#ControlName"

  2. Even though I used Selector="ToggleButton:checked #PlayorPauseIcon". and no errors occurred during build the project, The selector still not work.


Solution

  • To specify a namespace in Selector markup, you need to use a pipe symbol rather than a colon. Colons are instead used for pseudo-classes to be consistent with the way they are used in CSS, which inspired AvaloniaUI.

    <Style Selector="ToggleButton:checked materialIcons|MaterialIcon">