.net 如何反转 BooleanToVisibilityConverter?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/534575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I invert BooleanToVisibilityConverter?
提问by Atif Aziz
I'm using a BooleanToVisibilityConverterin WPF to bind the Visibilityproperty of a control to a Boolean. This works fine, but I'd like one of the controls to hide if the boolean is true, and show if it's false.
我BooleanToVisibilityConverter在 WPF 中使用 a将Visibility控件的属性绑定到Boolean. 这工作正常,但我希望其中一个控件隐藏布尔值是否为true,并显示它是否为false。
采纳答案by Steve Mitcham
Implement your own implementation of IValueConverter. A sample implementation is at
实现您自己的 IValueConverter 实现。示例实现位于
http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
In your Convert method, have it return the values you'd like instead of the defaults.
在您的 Convert 方法中,让它返回您想要的值而不是默认值。
回答by Atif Aziz
Instead of inverting, you can achieve the same goal by using a generic IValueConverterimplementation that can convert a Boolean value to configurabletarget values for true and false. Below is one such implementation:
您可以通过使用IValueConverter可将布尔值转换为 true 和 false 的可配置目标值的通用实现来实现相同的目标,而不是反转。下面是一个这样的实现:
public class BooleanConverter<T> : IValueConverter
{
public BooleanConverter(T trueValue, T falseValue)
{
True = trueValue;
False = falseValue;
}
public T True { get; set; }
public T False { get; set; }
public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is bool && ((bool) value) ? True : False;
}
public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is T && EqualityComparer<T>.Default.Equals((T) value, True);
}
}
Next, subclass it where Tis Visibility:
其次,它的子类,其中T是Visibility:
public sealed class BooleanToVisibilityConverter : BooleanConverter<Visibility>
{
public BooleanToVisibilityConverter() :
base(Visibility.Visible, Visibility.Collapsed) {}
}
Finally, this is how you could use BooleanToVisibilityConverterabove in XAML and configure it to, for example, use Collapsedfor true and Visiblefor false:
最后,这就是您可以如何BooleanToVisibilityConverter在 XAML 中使用上述内容并将其配置为,例如,Collapsed用于 true 和Visible用于 false:
<Application.Resources>
<app:BooleanToVisibilityConverter
x:Key="BooleanToVisibilityConverter"
True="Collapsed"
False="Visible" />
</Application.Resources>
This inversion is useful when you want to bind to a Boolean property named IsHiddenas opposed IsVisible.
当您想要绑定到名为IsHiddenas contrast的布尔属性时,此反转很有用IsVisible。
回答by Simon
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
public sealed class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var flag = false;
if (value is bool)
{
flag = (bool)value;
}
else if (value is bool?)
{
var nullable = (bool?)value;
flag = nullable.GetValueOrDefault();
}
if (parameter != null)
{
if (bool.Parse((string)parameter))
{
flag = !flag;
}
}
if (flag)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var back = ((value is Visibility) && (((Visibility)value) == Visibility.Visible));
if (parameter != null)
{
if ((bool)parameter)
{
back = !back;
}
}
return back;
}
}
and then pass a true or false as the ConverterParameter
然后传递一个 true 或 false 作为 ConverterParameter
<Grid.Visibility>
<Binding Path="IsYesNoButtonSetVisible" Converter="{StaticResource booleanToVisibilityConverter}" ConverterParameter="true"/>
</Grid.Visibility>
回答by Michael Hohlios
Write your own is the best solution for now. Here is an example of a Converter that can do both way Normal and Inverted. If you have any problems with this just ask.
自己编写是目前最好的解决方案。下面是一个转换器的例子,它可以在正常和反转两种方式下进行。如果您对此有任何问题,请询问。
[ValueConversion(typeof(bool), typeof(Visibility))]
public class InvertableBooleanToVisibilityConverter : IValueConverter
{
enum Parameters
{
Normal, Inverted
}
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var boolValue = (bool)value;
var direction = (Parameters)Enum.Parse(typeof(Parameters), (string)parameter);
if(direction == Parameters.Inverted)
return !boolValue? Visibility.Visible : Visibility.Collapsed;
return boolValue? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return null;
}
}
<UserControl.Resources>
<Converters:InvertableBooleanToVisibilityConverter x:Key="_Converter"/>
</UserControl.Resources>
<Button Visibility="{Binding IsRunning, Converter={StaticResource _Converter}, ConverterParameter=Inverted}">Start</Button>
回答by Cameron MacFarland
There's also the WPF Convertersproject on Codeplex. In their documentation they say you can use their MapConverterto convert from Visibility enumeration to bool
Codeplex上还有WPF Converters项目。在他们的文档中,他们说您可以使用他们的MapConverter将 Visibility 枚举转换为 bool
<Label>
<Label.Visible>
<Binding Path="IsVisible">
<Binding.Converter>
<con:MapConverter>
<con:Mapping From="True" To="{x:Static Visibility.Visible}"/>
<con:Mapping From="False" To="{x:Static Visibility.Hidden}"/>
</con:MapConverter>
</Binding.Converter>
</Binding>
</Label.Visible>
</Label>
回答by Marat Batalandabad
One more way to Bind ViewModel Boolean Value (IsButtonVisible) with xaml Control Visibility Property. No coding, No converting, just styling.
使用 xaml 控件可见性属性绑定 ViewModel 布尔值 (IsButtonVisible) 的另一种方法。没有编码,没有转换,只是样式。
<Style TargetType={x:Type Button} x:Key="HideShow">
<Style.Triggers>
<DataTrigger Binding="{Binding IsButtonVisible}" Value="False">
<Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>
</Style.Triggers>
</Style>
<Button Style="{StaticResource HideShow}">Hello</Button>
回答by Ross Oliver
Or the real lazy mans way, just make use of what is there already and flip it:
或者真正的懒人方式,只需利用已有的东西并翻转它:
public class InverseBooleanToVisibilityConverter : IValueConverter
{
private BooleanToVisibilityConverter _converter = new BooleanToVisibilityConverter();
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var result = _converter.Convert(value, targetType, parameter, culture) as Visibility?;
return result == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var result = _converter.ConvertBack(value, targetType, parameter, culture) as bool?;
return result == true ? false : true;
}
}
回答by Haim Bendanan
If you don't like writing custom converter, you could use data triggers to solve this:
如果你不喜欢编写自定义转换器,你可以使用数据触发器来解决这个问题:
<Style.Triggers>
<DataTrigger Binding="{Binding YourBinaryOption}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding YourBinaryOption}" Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
回答by xr280xr
Here's one I wrote and use a lot. It uses a boolean converter parameter that indicates whether or not to invert the value and then uses XOR to perform the negation:
这是我写的并且经常使用的一个。它使用一个布尔转换器参数来指示是否反转值,然后使用 XOR 执行否定:
[ValueConversion(typeof(bool), typeof(System.Windows.Visibility))]
public class BooleanVisibilityConverter : IValueConverter
{
System.Windows.Visibility _visibilityWhenFalse = System.Windows.Visibility.Collapsed;
/// <summary>
/// Gets or sets the <see cref="System.Windows.Visibility"/> value to use when the value is false. Defaults to collapsed.
/// </summary>
public System.Windows.Visibility VisibilityWhenFalse
{
get { return _visibilityWhenFalse; }
set { _visibilityWhenFalse = value; }
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool negateValue;
Boolean.TryParse(parameter as string, out negateValue);
bool val = negateValue ^ System.Convert.ToBoolean(value); //Negate the value when negateValue is true using XOR
return val ? System.Windows.Visibility.Visible : _visibilityWhenFalse;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool negateValue;
Boolean.TryParse(parameter as string, out negateValue);
if ((System.Windows.Visibility)value == System.Windows.Visibility.Visible)
return true ^ negateValue;
else
return false ^ negateValue;
}
}
Here's an XOR truth table for reference:
这是一个 XOR 真值表供参考:
XOR
x y XOR
---------
0 0 0
0 1 1
1 0 1
1 1 0
回答by Rhyous
I just did a post on this. I used a similar idea as Michael Hohlios did. Only, I used Properties instead of using the "object parameter".
我刚刚发了一篇关于这个的帖子。我使用了与 Michael Hohlios 类似的想法。只是,我使用了属性而不是使用“对象参数”。
Binding Visibility to a bool value in WPF
Using Properties makes it more readable, in my opinion.
在我看来,使用属性将可见性绑定到 WPF 中的 bool 值使其更具可读性。
<local:BoolToVisibleOrHidden x:Key="BoolToVisConverter" Collapse="True" Reverse="True" />

