Data Trigger to Inverse the value of IsChecked Property of checkbox for binding

Many times we may require to enable / disable controls in WPF on the check state of a checkbox in the window. In XAML we want to enable our control if checkbox is checked and disable if it is unchecked, this can be done very easily by using below binding


<StackPanel Orientation="Horizontal"> <CheckBox x:Name="chkHandler" Content="Enable Controls"> </CheckBox> <TextBlock Width="50" />
<TextBox x:Name="Sample" Text="Sample Text Box" 
IsEnabled="{Binding Path=IsChecked, ElementName=chkHandler}">
</TextBox> </StackPanel>



In above code there is a checkbox "chkHandler", which will handle the enable or disable state of Textbox called "Sample".



Now suppose our scenario is opposite to this, we have to enable the control if checkbox is unchecked and disable the control if it is checked. This scenario can not be achieved directly by binding discussed in above code. Because if checkbox is checked than its value will be true, and to disable the control we will have to provide false the IsEnabled property of textbox.

To achieve this we will have to use data trigger which will inverse the value of the checkbox.

<StackPanel Orientation="Horizontal">
  <CheckBox x:Name="chkHandler" Content="Disable Controls"></CheckBox>
  <TextBlock Width="50"></TextBlock>
  <TextBox x:Name="Sample" Text="Sample Text Box">
   <TextBox.Style>
    <Style>
     <Style.Triggers>
      <DataTrigger Binding='{Binding Path=IsChecked, ElementName=chkHandler}' Value='True'>
       <Setter Property='TextBox.IsEnabled' Value='False'/>
        </DataTrigger>
      </Style.Triggers>
     </Style>
    </TextBox.Style>
   </TextBox>
  </StackPanel>


No comments:

Post a Comment