winrt-xamlwinui-3

WinUI3 CheckBox content style


I'm trying to change the color of a CheckBox text, but it doesn't work. Here is what I tried:

<CheckBox x:Name="OptionCheckBox"
          Foreground="#FFFFFFF"
          Content="PDF">
    <CheckBox.Resources>
        <Style TargetType="CheckBox">
            <Setter Property="Foreground"
                    Value="Blue" />
            <Setter Property="FontSize"
                    Value="16" />
            <Setter Property="Padding"
                    Value="5" />
            <Setter Property="HorizontalAlignment"
                    Value="Left" />
        </Style>
    </CheckBox.Resources>
</CheckBox>

Why doesn't it work, what can I use instead?


Solution

  • You can find the default Style as explained in Where are the default WinUI3 control style files?. Reading generic.xaml, the Foreground is solely managed by VisualStateManager and so the Brush set in a Style would be overriden. I think Faywang's explanation on UWP in Checkbox content color can't be set in UWP can apply to WinUI as well.

    That said, if you don't mind to fix the Brush, the easiest solution is to define a ContentTemplate in the Style and directly set Foreground of TextBlock.

    <Style TargetType="CheckBox">
        ...
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Foreground="Blue"
                               Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}"/>                             
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>