在 WPF MenuItem 中,可以使用布尔值的相反值
In WPF MenuItem, it it possible to use the opposite value of a bool
在 WPF 中,我有两个相互相反的菜单项(X 勾选,然后 Y 未勾选,反之亦然)。
是否可以使用单个 bool 属性 来绑定这两个?
例如下面的例子,我使用了 !IsX 但它不起作用!
<MenuItem Header="X or Y">
<MenuItem IsCheckable="True" Header="Is X?" IsChecked="{Binding Path=IsX, Mode=TwoWay}" />
<MenuItem IsCheckable="True" Header="Is Y?" IsChecked="{Binding Path=!IsX, Mode=TwoWay}" />
</MenuItem>
您需要为此编写自定义转换器:
[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)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
#endregion
}
然后在您的标记中:
<MenuItem Header="X or Y">
<MenuItem IsCheckable="True" Header="Is X?" IsChecked="{Binding Path=IsX, Mode=TwoWay}" />
<MenuItem IsCheckable="True" Header="Is Y?" IsChecked="{Binding Path=IsX, Mode=TwoWay, Converter={StaticResource InverseBooleanConverter}}" />
</MenuItem>
您还应该在资源文件中创建一个实例
在 WPF 中,我有两个相互相反的菜单项(X 勾选,然后 Y 未勾选,反之亦然)。
是否可以使用单个 bool 属性 来绑定这两个?
例如下面的例子,我使用了 !IsX 但它不起作用!
<MenuItem Header="X or Y">
<MenuItem IsCheckable="True" Header="Is X?" IsChecked="{Binding Path=IsX, Mode=TwoWay}" />
<MenuItem IsCheckable="True" Header="Is Y?" IsChecked="{Binding Path=!IsX, Mode=TwoWay}" />
</MenuItem>
您需要为此编写自定义转换器:
[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)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
#endregion
}
然后在您的标记中:
<MenuItem Header="X or Y">
<MenuItem IsCheckable="True" Header="Is X?" IsChecked="{Binding Path=IsX, Mode=TwoWay}" />
<MenuItem IsCheckable="True" Header="Is Y?" IsChecked="{Binding Path=IsX, Mode=TwoWay, Converter={StaticResource InverseBooleanConverter}}" />
</MenuItem>
您还应该在资源文件中创建一个实例