I have two CheckBoxes in XAML. When the first one is unchecked, I want the second one to be unchecked. But when the first one is checked, I don't want anything to happen with the second one. I also want both CheckBoxes checked by default. This seems like it should be very simple with a DataTrigger
, but I can't quite get it. I know this would be trivial to accomplish in code with event handlers, but I wanted to do it in XAML. Here is what I have:
<CheckBox Name="CheckBox1" Content="CheckBox1" IsChecked="True" />
<CheckBox Name="CheckBox2" Content="CheckBox2">
<CheckBox.Style>
<Style TargetType="{x:Type CheckBox}">
<Setter Property="CheckBox.IsChecked" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=CheckBox1, Path=IsChecked}" Value="False">
<Setter Property="CheckBox.IsChecked" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</CheckBox.Style>
</CheckBox>
Both CheckBoxes start off checked, and when I uncheck CheckBox1, CheckBox2 is also unchecked, correctly. But when I check CheckBox1, CheckBox2 is incorrectly checked also. I tried several variations of this with no luck. If I remove the first Setter
it works correctly, but then CheckBox2 doesn't start out checked.
You can try the other way around using event trigger directly from CheckBox1 :
<CheckBox Name="CheckBox1" Content="CheckBox1" IsChecked="True">
<CheckBox.Triggers>
<EventTrigger RoutedEvent="CheckBox.Unchecked">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="CheckBox2" Storyboard.TargetProperty="(CheckBox.IsChecked)">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</CheckBox.Triggers>
</CheckBox>
<CheckBox Name="CheckBox2" Content="CheckBox2" IsChecked="True"/>
Alternatively If You want this too look cleaner, You might explore : Microsoft.Xaml.Behaviors.* packages.
Problem with Your solution was, that the initial <Setter../> that You used to set the initial value of CheckBox, has been repeatedly working alongside the DataTrigger.