vendredi 12 août 2022

Change the background colour of a CheckBox using DataTriggers

I'd like the background of my CheckBox to change colour depending on if it matches a pre-defined bool (not just if it's Checked or Unchecked). The problem is that this looks poor if you do it to the CheckBox alone, so I've wrapped the CheckBox in a Grid and set the background of the Grid instead. My issue now is that I want to pull out this style so I can reuse it for my other Checkbox

Here is my XAML:

<Grid Margin="5 10 0 0">
    <CheckBox Name="cbJimbo" Content="JIMBO" FontSize="12"
    IsChecked="{Binding MyObject.Jimbo}"                                                                
    Style="{StaticResource CheckBoxStyle}"/>
    <Grid.Style>
        <Style TargetType="Grid">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=cbJimbo, Path=Background}" Value="Yellow">
                    <Setter Property="Background" Value="Yellow" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Grid.Style>
</Grid>

What is the best way to refactor this?

In the interest of completeness (Although not entirely relevant) here is the CheckBox style, which determines if the CheckBox matches the default value and then sets the CheckBox background in a too subtle fashion. Also relevant as my Grid is currently bound to the background of this Checkbox:

<Style x:Key="ValidationCheckBox" TargetType="CheckBox" BasedOn="{StaticResource {x:Type CheckBox}}">
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <StackPanel>
                    <AdornedElementPlaceholder x:Name="placeholder"/>
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self},
        Path=(Validation.Errors)/ErrorContent.ErrorType}" Value="{x:Static wrapper:ErrorTypeEnum.Default}">
            <Setter Property="Background" Value="Yellow"/>
        </DataTrigger>
    </Style.Triggers>
</Style>



Aucun commentaire:

Enregistrer un commentaire