togglebuttonavaloniaui

How to set the background colour of a checked toggle button in Avalonia UI Desktop application


I am trying to set the background colour of a checked toggle button in Avalonia UI.

The following style sets the padding of all checked toggle buttons within the user control to 40, but the background colour remains the default blue instead of red.

    <UserControl.Styles>
        <Style Selector="ToggleButton:checked">
            <Setter Property="Background" Value="Red"/>
            <Setter Property="Padding" Value="40"/>
        </Style>
    </UserControl.Styles>

Here is an example where "Option 1" is checked.

enter image description here

How can I override the default background colour of a checked toggle button?


Solution

  • When using Pseudoclasses on the button your selector has to target the ContentPresenter on the button template.

    <Style Selector="ToggleButton">
      <!-- Default setters here -->
    
      <Style Selector="^:checked /template/ ContentPresenter#PART_ContentPresenter">
        <!-- Checked setters here -->
      </Style>
    </Style>
    

    Optionally you can leave off #PART_ContentPresenter, but that will target any content presenter on the control so be careful doing that. In the default template the button only has one.