我所拥有的是具有IsReadOnly
属性的对象。 如果此属性为true,我想将Button上的IsEnabled
属性(例如)设置为false。
我想相信我可以像IsEnabled="{Binding Path=!IsReadOnly}"
那样轻松地做到这一点,但是这并不适用于WPF。
我不得不经历所有的风格设置吗? 对于像将一个bool设置为另一个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>
#1楼
您可以使用ValueConverter为您反转bool属性。
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
}
#2楼
您是否考虑过IsNotReadOnly
属性? 如果绑定的对象是MVVM域中的ViewModel,则附加属性非常有意义。 如果它是直接实体模型,您可以考虑组合并向表单呈现实体的专用ViewModel。
#3楼
我建议使用https://quickconverter.codeplex.com/
然后反转布尔值就像这样简单: <Button IsEnabled="{qc:Binding '!$P', P={Binding IsReadOnly}}" />
这加快了编写转换器通常所需的时间。
#4楼
使用标准装订,您需要使用看起来有风的转换器。 因此,我建议您查看我的项目CalcBinding ,它是专门为解决此问题而开发的。 使用高级绑定,您可以直接在xaml中编写具有许多源属性的表达式。 说,你可以这样写:
<Button IsEnabled="{c:Binding Path=!IsReadOnly}" />
要么
<Button Content="{c:Binding ElementName=grid, Path=ActualWidth+Height}"/>
要么
<Label Content="{c:Binding A+B+C }" />
要么
<Button Visibility="{c:Binding IsChecked, FalseToVisibility=Hidden}" />
其中A,B,C,IsChecked - viewModel的属性,它将正常工作
祝好运!
#5楼
不知道这是否与XAML相关,但在我的简单Windows应用程序中,我手动创建了绑定并添加了一个Format事件处理程序。
public FormMain() {
InitializeComponent();
Binding argBinding = new Binding("Enabled", uxCheckBoxArgsNull, "Checked", false, DataSourceUpdateMode.OnPropertyChanged);
argBinding.Format += new ConvertEventHandler(Binding_Format_BooleanInverse);
uxTextBoxArgs.DataBindings.Add(argBinding);
}
void Binding_Format_BooleanInverse(object sender, ConvertEventArgs e) {
bool boolValue = (bool)e.Value;
e.Value = !boolValue;
}
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3188451