猿问

如何反转BooleanToVisibilityConverter?

BooleanToVisibilityConverter在WPF中使用Visibility,将控件的属性绑定到Boolean。这可以正常工作,但我希望其中一个控件可以隐藏boolean是否为true,并显示是否为false



素胚勾勒不出你
浏览 746回答 3
3回答

哆啦的时光机

通过使用IValueConverter将布尔值转换为true和false的可配置目标值的通用实现,您可以实现相同的目标,而不是取反。以下是一种这样的实现:public class BooleanConverter<T> : IValueConverter{&nbsp; &nbsp; public BooleanConverter(T trueValue, T falseValue)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; True = trueValue;&nbsp; &nbsp; &nbsp; &nbsp; False = falseValue;&nbsp; &nbsp; }&nbsp; &nbsp; public T True { get; set; }&nbsp; &nbsp; public T False { get; set; }&nbsp; &nbsp; public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return value is bool && ((bool) value) ? True : False;&nbsp; &nbsp; }&nbsp; &nbsp; public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return value is T && EqualityComparer<T>.Default.Equals((T) value, True);&nbsp; &nbsp; }}接下来,在以下位置T将其子类化Visibility:public sealed class BooleanToVisibilityConverter : BooleanConverter<Visibility>{&nbsp; &nbsp; public BooleanToVisibilityConverter() :&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; base(Visibility.Visible, Visibility.Collapsed) {}}最后,这是您可以BooleanToVisibilityConverter在XAML中使用上述方法并将其配置为例如Collapsed用于true和Visiblefalse的方式:<Application.Resources>&nbsp; &nbsp; <app:BooleanToVisibilityConverter&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; x:Key="BooleanToVisibilityConverter"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; True="Collapsed"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; False="Visible" /></Application.Resources>当您要绑定到名为IsHidden相反的布尔属性时,此反转非常有用IsVisible。
随时随地看视频慕课网APP
我要回答