我是WPF的入门者,有些事情我似乎无法弄清楚。

我有一个CheckBox,当未选择RadioButton时我想禁用它。
我当前的语法是:

<CheckBox IsEnabled="{Binding ElementName=rbBoth, Path=IsChecked}">Show all</CheckBox>

因此,基本上,我希望IsEnabled可以采用与当前提供的绑定(bind)表达式相反的值。

我怎样才能做到这一点?谢谢。

最佳答案

您需要使用所谓的值转换器(实现IValueConverter的类)。此类的一个非常基本的示例如下所示。 (注意剪辑...)

public class NegateConverter : IValueConverter
{

    public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
    {
        if ( value is bool ) {
            return !(bool)value;
        }
        return value;
    }

    public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
    {
        if ( value is bool ) {
            return !(bool)value;
        }
        return value;
    }

}

然后将其包含在XAML中,您将执行以下操作:
<UserControl xmlns:local="clr-namespace:MyNamespace">
    <UserControl.Resources>
        <local:NegateConverter x:Key="negate" />
    </UserControl.Resources>

    ...
    <CheckBox IsEnabled="{Binding IsChecked, ElementName=rbBoth, Converter={StaticResource negate}}"
              Content="Show all" />

</UserControl>

关于IsEnabled的WPF元素数据绑定(bind)(但为false),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3099402/

10-12 12:40
查看更多