[英]WPF - Is it possible to negate the result of a data binding expression?
I know this works fine: 我知道这很好用:
<TextBox IsEnabled="{Binding ElementName=myRadioButton, Path=IsChecked}" />
...but what I really want to do is negate the result of the binding expression similar to below (psuedocode). ...但我真正想做的是否定类似于下面的结合表达式的结果(伪代码)。 Is this possible? 这可能吗?
<TextBox IsEnabled="!{Binding ElementName=myRadioButton, Path=IsChecked}" />
You can do this using an IValueConverter: 您可以使用IValueConverter执行此操作:
public class NegatingConverter : IValueConverter
{
public object Convert(object value, ...)
{
return !((bool)value);
}
}
and use one of these as the Converter of your Binding. 并使用其中一个作为绑定的转换器。
If you want want a result type other than bool, I've recently started using the ConverterParameter to give myself the option of negating the resulting value from my converters. 如果你想要一个除bool之外的结果类型,我最近开始使用ConverterParameter给自己选择否定转换器的结果值。 Here's an example: 这是一个例子:
[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;
}
...
This converter converts a bool to a System.Windows.Visibility. 此转换器将bool转换为System.Windows.Visibility。 The parameter allows it to negate the bool before converting in case you want the inverse behavior. 如果您想要反向行为,该参数允许它在转换之前否定bool。 You could use it in an element like this: 你可以在这样的元素中使用它:
Visibility="{Binding Path=MyBooleanProperty, Converter={StaticResource boolVisibilityConverter}, ConverterParameter=true}"
不幸的是,你不能直接在Binding表达式上执行运算符,例如否定...我建议使用ValueConverter来反转布尔值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.