如何绑定在WPF逆布尔属性? [英] How to bind inverse boolean properties in WPF?
问题描述
我已经是一个对象,它有一个的IsReadOnly
属性。如果此属性是真的,我想在一个按钮设置的IsEnabled
属性,(例如),为false。
我愿意相信,我可以容易地做到这一点的的IsEnabled ={绑定路径=!的IsReadOnly}
但是,这并不与WPF飞。
我是降级不必经过所有的样式设置?似乎太罗嗦了一些简单为一个布尔值设置到另一个布尔逆。
< Button.Style>
<风格的TargetType ={X:类型按钮}>
< Style.Triggers>
< DataTrigger绑定={绑定路径=的IsReadOnly}值=真>
< setter属性=IsEnabled的VALUE =FALSE/>
< / DataTrigger>
< DataTrigger绑定={绑定路径=的IsReadOnly}值=FALSE>
< setter属性=IsEnabled的VALUE =真/>
< / DataTrigger>
< /Style.Triggers>
< /样式和GT;
< /Button.Style>
您可以使用ValueConverter是反转一个bool属性你。
XAML:
的IsEnabled ={绑定路径=的IsReadOnly,转换器= {的StaticResource InverseBooleanConverter}}
转换:
[ValueConversion(typeof运算(布尔)的typeof(布尔))]
公共类InverseBooleanConverter:的IValueConverter
{
#地区的IValueConverter会员
公共对象转换(对象的值,类型TARGETTYPE,对象参数,
System.Globalization.CultureInfo文化)
{
如果(TARGETTYPE!= typeof运算(布尔))
抛出新的InvalidOperationException异常(我们的目标是布尔);
返回(布尔)值!;
}
公共对象ConvertBack(对象的值,类型TARGETTYPE,对象参数,
System.Globalization.CultureInfo文化)
{
抛出新NotSupportedException异常();
}
#endregion
}
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.
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>
You can use a ValueConverter that inverts a bool property for you.
XAML:
IsEnabled="{Binding Path=IsReadOnly, Converter={StaticResource InverseBooleanConverter}}"
Converter:
[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屋!