简体   繁体   中英

Bind visibility of a control to combobox selection

I have a combobox which is bound to an Enum datatype. Right now the combobox binding works fine but when I tried to bind the visibility of a checkbox to the combobox selection, this binding is not working as expected. What I wanted to do was whenever the combobox selection is "Restore", I want a checkbox to be visible. Below is the code that I am using.

 <CheckBox.Style>
     <Style TargetType="CheckBox">
       <Style.Triggers>
          <DataTrigger Binding="{Binding ElementName=cmbOperation, Path=SelectedValue}" Value="Restore">
              <Setter Property="Visibility" Value="Visible"></Setter>
          </DataTrigger>
      </Style.Triggers>
   </Style>
</CheckBox.Style>

I tried changing the Path between SelectedValue, SelectedItem , SelectedValue.TosString() (hopelessly) but I am not getting the checkbox to change its visibility whenever the combobox has "Restore" as its selection. Should I be making any changes in the Enum that I am binding to the Combobox ? If not, what else am I doing wrong?

I'm willing to bet that you've set Visibility on the CheckBox in the XAML:

<CheckBox
    Visibility="Collapsed"
    >

However, due to the rules of Dependency Property Value Precedence in WPF, that will override anything that happens in the Style. This is by design and it's not a bad idea when you think through all the implications, but it bites everybody who's new to WPF.

It's an easy fix: Just set the starting value in a Setter in the Style. What the Style does, the Style can undo.

<CheckBox
    >
    <CheckBox.Style>
        <Style TargetType="CheckBox">
            <Setter Property="Visibility" Value="Collapsed" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=cmbOperation, Path=SelectedValue}" Value="Restore">
                    <Setter Property="Visibility" Value="Visible" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </CheckBox.Style>
</CheckBox>

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