如何在 WPF 中绑定反向布尔属性? [英] How to bind inverse boolean properties in WPF?
问题描述
我拥有的是一个具有 IsReadOnly
属性的对象.如果此属性为 true,我想将按钮上的 IsEnabled
属性(例如)设置为 false.
What I have is an object that has an IsReadOnly
property. If this property is true, I would like to set the IsEnabled
property on a Button, ( for example ), to false.
我想相信我可以像 IsEnabled="{Binding Path=!IsReadOnly}"
一样轻松地做到这一点,但这在 WPF 中并不适用.
I would like to believe that I can do it as easily as IsEnabled="{Binding Path=!IsReadOnly}"
but that doesn't fly with WPF.
我是否必须完成所有样式设置?对于将一个布尔值设置为另一个布尔值的倒数这样简单的事情来说,这似乎太冗长了.
Am I relegated to having to go through all of the style settings? Just seems too wordy for something as simple as setting one bool to the inverse of another bool.
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsReadOnly}" Value="True">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
<DataTrigger Binding="{Binding Path=IsReadOnly}" Value="False">
<Setter Property="IsEnabled" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
推荐答案
您可以使用 ValueConverter 为您反转 bool 属性.
You can use a ValueConverter that inverts a bool property for you.
XAML:
IsEnabled="{Binding Path=IsReadOnly, Converter={StaticResource InverseBooleanConverter}}"
转换器:
[ValueConversion(typeof(bool), typeof(bool))]
public class InverseBooleanConverter: IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
这篇关于如何在 WPF 中绑定反向布尔属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!