繁体   English   中英

WPF将ComboBox与CheckBox绑定

[英]WPF bind ComboBox with CheckBox

我想将ComboBox与CheckBox绑定,以便在未选中 CheckBox时启用ComboBox。 我可以直接在xaml文件中执行此操作,而无需在代码中添加任何其他变量吗?
在下面的代码中,当myCheckBox 被选中时,myComboBox被启用。

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

您需要一个转换器将布尔值转换为它的取反值。 为了做到这一点,首先创建一个从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();
    }
}

然后,您需要在资源中添加转换器,如下所示:

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

最后,只需将转换器添加到绑定中,如下所示:

<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