Question

I have the following DataTrigger in a WPF form:

<CheckBox IsChecked="{Binding ConcentratorViewModel.Integrated}">
    <CheckBox.Style>
        <Style TargetType="{x:Type CheckBox}">
            <Setter Property="Margin" Value="0,10,0,0"/>
            <Setter Property="Width" Value="20"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <!--<Setter Property="IsEnabled" Value="False"/>-->
            <!--<Setter Property="IsChecked" Value="False"/>-->

             <Style.Triggers>
                 <DataTrigger Binding="{Binding ConcentratorViewModel.Manufacturer}" Value="ZIV">
                     <Setter Property="Background" Value="Red"/>
                     <Setter Property="IsChecked" Value="True"/>
                 </DataTrigger>

                 <DataTrigger Binding="{Binding ConcentratorViewModel.Manufacturer}" Value="Landis+Gyr">
                     <Setter Property="IsChecked" Value="False"/>                                    
                 </DataTrigger>
            </Style.Triggers>
        </Style>
    </CheckBox.Style>
</CheckBox>

The CheckBox must be Checked or Unchecked depending on the selected manufacturer. I added a converter to see the value on the trigger and it's correct. I've also added the Background property and it changes correctly, but the IsChecked doesn't work.

Was it helpful?

Solution

Well you need to move the IsChecked Binding inside the Style. Setting it directly on the Checkbox gives it precedence and the Trigger's cannot change that value.

So something like:

<CheckBox>
  <CheckBox.Style>
    <Style TargetType="{x:Type CheckBox}">
      <Setter Property="Margin"
              Value="0,10,0,0" />
      <Setter Property="Width"
              Value="20" />
      <Setter Property="VerticalAlignment"
              Value="Center" />
      <Setter Property="IsChecked"
              Value="{Binding ConcentratorViewModel.Integrated}" />
      <Style.Triggers>
        <DataTrigger Binding="{Binding ConcentratorViewModel.Manufacturer}"
                     Value="ZIV">
          <Setter Property="Background"
                  Value="Red" />
          <Setter Property="IsChecked"
                  Value="True" />
        </DataTrigger>
        <DataTrigger Binding="{Binding ConcentratorViewModel.Manufacturer}"
                     Value="Landis+Gyr">
          <Setter Property="IsChecked"
                  Value="False" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </CheckBox.Style>
</CheckBox>

Note:

Remember by doing this, your Binding only applies when the DataTrigger's do not evaluate to "True". Thus if your Manufacturer property is "ZIV" or "Landis+Gyr" then your Integrated property is not going to see any CheckBox updates even with a TwoWay binding as it just isn't being used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top