WPF - 是否有可能否定数据绑定表达式的结果?

Tay*_*ese 10 .net c# data-binding wpf

我知道这很好用:

<TextBox IsEnabled="{Binding ElementName=myRadioButton, Path=IsChecked}" />
Run Code Online (Sandbox Code Playgroud)

...但我真正想做的是否定类似于下面的结合表达式的结果(伪代码).这可能吗?

<TextBox IsEnabled="!{Binding ElementName=myRadioButton, Path=IsChecked}" />
Run Code Online (Sandbox Code Playgroud)

ito*_*son 12

您可以使用IValueConverter执行此操作:

public class NegatingConverter : IValueConverter
{
  public object Convert(object value, ...)
  {
    return !((bool)value);
  }
}
Run Code Online (Sandbox Code Playgroud)

并使用其中一个作为绑定的转换器.


xr2*_*0xr 5

如果你想要一个除bool之外的结果类型,我最近开始使用ConverterParameter给自己选择否定转换器的结果值.这是一个例子:

[ValueConversion(typeof(bool), typeof(System.Windows.Visibility))]
public class BooleanVisibilityConverter : IValueConverter
{
    System.Windows.Visibility _visibilityWhenFalse = System.Windows.Visibility.Collapsed;

    /// <summary>
    /// Gets or sets the <see cref="System.Windows.Visibility"/> value to use when the value is false. Defaults to collapsed.
    /// </summary>
    public System.Windows.Visibility VisibilityWhenFalse
    {
        get { return _visibilityWhenFalse; }
        set { _visibilityWhenFalse = value; }
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool negateValue;
        Boolean.TryParse(parameter as string, out negateValue);

        bool val = negateValue ^ (bool)value;  //Negate the value using XOR
        return val ? System.Windows.Visibility.Visible : _visibilityWhenFalse;
    }
    ...
Run Code Online (Sandbox Code Playgroud)

此转换器将bool转换为System.Windows.Visibility.该参数允许它在转换之前否定bool,以防您想要反向行为.你可以在这样的元素中使用它:

Visibility="{Binding Path=MyBooleanProperty, Converter={StaticResource boolVisibilityConverter}, ConverterParameter=true}"
Run Code Online (Sandbox Code Playgroud)