简体   繁体   中英

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

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM