C# WPF - Create a generic style trigger for multiple checkboxes defined within separate grids

109 Views Asked by At

I have 40+ checkboxes that are each within a separate grid on a view. The purpose for this is so I can easily set the background of the grid to yellow based on a certain condition. The snippet of code below works as expected.

The only downside to this is that I am currently having to copy this style and put it within each of the 40 checkboxes and bind to the element name. Therefore, my question is how do I make the grid style more generic so that I don't have to put the style within each checkbox and bind to the element name. Any advice would be greatly appreciated.

<Grid Margin="5 10 0 0">
       <CheckBox Name="cbValid" Content="VALID-CATEGORY" FontSize="12"
       IsChecked="{Binding Category.VALID_CATEGORY}"
       Style="{StaticResource CheckBoxStyle}"/>
       <Grid.Style>
            <Style TargetType="Grid">
                   <Style.Triggers>
                          <DataTrigger Binding="{Binding ElementName=cbValid, Path=Background}" Value="Yellow">
                               <Setter Property="Background" Value="Yellow" />
                          </DataTrigger>
                   </Style.Triggers>
            </Style>
       </Grid.Style>
</Grid>
1

There are 1 best solutions below

0
mm8 On

You shouldn't need the Grid if you create a custom template for your CheckBox.

Or you could use an implicit Grid style that binds the Background to the Background of its first child:

<Style TargetType="Grid">
    <Setter Property="Background"
            Value="{Binding Children[0].Background, RelativeSource={RelativeSource Self}}" />
</Style>