WPF: Bind Control Enabled to Checkbox Checked

July 23rd, 2009 by Mel Leave a reply »

This is a simple example of a nifty use of binding in WPF.

Say you have an element in your application such as a TextBox, ComboBox, or some RadioButtons that you want to keep disabled to the user unless the user checks a box. You may even want to disable a whole section of controls contained inside of a StackPanel or DockPanel.

Everything enabled

To accomplish this you bind the IsEnabled property of the target control (in this case a ComboBox) to the IsChecked property of the CheckBox.

XAML:

<StackPanel>
    <CheckBox x:Name="chkEnableBackup">Run Backup Sets</CheckBox>
 
    <StackPanel Orientation="Horizontal">
        <Label Margin="12,0,0,0">Run backup every</Label>
        <ComboBox Width="70" SelectedIndex="0"
          IsEnabled="{Binding ElementName=chkEnableBackup, Path=IsChecked}">
            <ComboBoxItem>Minute</ComboBoxItem>
            <ComboBoxItem>Hour</ComboBoxItem>
            <ComboBoxItem>Day</ComboBoxItem>
        </ComboBox>
    </StackPanel>
</StackPanel>

That’s it! Our result is that when the box is not checked the control is disabled.

Control disabled!

Advertisement

5 comments

  1. santhi says:

    Thanks a Lot !!
    Very easy and perfect…

  2. Chetan Sheladiya says:

    Small & Sweet Example

  3. Erin says:

    Thats actually pretty cool.

Leave a Reply