简体   繁体   English

WPF将ComboBox与CheckBox绑定

[英]WPF bind ComboBox with CheckBox

I would like to bind a ComboBox with a CheckBox so that the ComboBox is enabled when the CheckBox is not checked . 我想将ComboBox与CheckBox绑定,以便在未选中 CheckBox时启用ComboBox。 Can I do that directly in the xaml file, without adding any additional variable in the code? 我可以直接在xaml文件中执行此操作,而无需在代码中添加任何其他变量吗?
In the code below, myComboBox is enabled when myCheckBox is ckecked . 在下面的代码中,当myCheckBox 被选中时,myComboBox被启用。

<ComboBox Name="myComboBox" SelectedIndex="0" 
     IsEnabled="{Binding ElementName=myCheckBox, Path=IsChecked}">

You need a converter to convert the Boolean values to it's inverted value. 您需要一个转换器将布尔值转换为它的取反值。 In order to do that first create a class the inherits from IValueConverter like this: 为了做到这一点,首先创建一个从IValueConverter继承的类,如下所示:

public sealed class InvertedBooleanConverter : IValueConverter
{
    public Object Convert( Object value, Type targetType, Object parameter, CultureInfo culture )
    {
        if ( value is Boolean )
        {
            return (Boolean)value ? false : true;
        }

        return null;
    }


    public Object ConvertBack( Object value, Type targetType, Object parameter, CultureInfo culture )
    {
        throw new NotImplementedException();
    }
}

Then you need to add the converter in the resources like this: 然后,您需要在资源中添加转换器,如下所示:

<Window.Resources>
    <local:InvertedBooleanConverter x:Key="InvertedBooleanConverter" />
</Window.Resources>

And lastly just add the converter to the binding like this: 最后,只需将转换器添加到绑定中,如下所示:

<ComboBox Name="myComboBox"
          SelectedIndex="0"
          IsEnabled="{Binding ElementName=myCheckBox, Path=IsChecked, Converter={StaticResource InvertedBooleanConverter}}">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM