WPF元素数据绑定IsEnabled(但为false) [英] WPF element databinding for IsEnabled (but for false)
问题描述
我有一个复选框
RadioButton
未选择。 我当前的语法是:
< CheckBox IsEnabled ={Binding ElementName = rbBoth,Path = IsChecked} >显示全部< / CheckBox>
所以基本上,我想IsEnabled取与我目前提供的绑定表达式相反的值。
我该如何做?感谢。
您需要使用所谓的值转换器(实现IValueConverter的类)。一个非常基本的例子一个类如下所示。 (观看剪辑...)
public class NegateConverter:IValueConverter
{
公共对象转换(对象值,类型targetType,对象参数,CultureInfo文化)
{
if(value is bool){
return!(bool)value;
}
返回值;
}
public object ConvertBack(对象值,类型targetType,对象参数,CultureInfo文化)
{
if(value is bool){
return !(bool)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>
I'm a starter in WPF, and there's something I can't seem to figure out.
I have a CheckBox
that I would like to disable when a RadioButton
is not selected.
My current syntax is:
<CheckBox IsEnabled="{Binding ElementName=rbBoth, Path=IsChecked}">Show all</CheckBox>
So basically, I want IsEnabled to take the opposite value than the binding expression I'm currently supplying.
How can I do this? Thanks.
You need to use what's called a value converter (a class that implements IValueConverter.) A very basic example of such a class is shown below. (Watch for clipping...)
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;
}
}
Then to include it in your XAML you would do something like:
<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>
这篇关于WPF元素数据绑定IsEnabled(但为false)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!