我有一个转换器,我可以在代码中设置如下属性:
tabAssumptions.SetBinding(UIElement.VisibilityProperty, new Binding("CurrentPhase.IsWholeScheme") { Converter = new BoolToVisibilityConverter { Inverse = true } });
在 XAML 中使用时如何设置转换器的 Inverse 属性?
我的 BoolToVisibilityConverter 如下。您可以将其用作资源:
<converters:BoolToVisibilityConverter x:Key="FalseToHidden"
TrueValue="Visible" FalseValue="Hidden" />
或将其用作 XAML 中的 MarkupExtension 内联:
Visibility="{Binding MyFlag,
Converter={vc:BoolToVisibilityConverter
FalseValue=Collapsed, TrueValue=Visible}}"
C#
public class BoolToVisibilityConverter : BoolToValueConverter<Visibility>
{
#region Constructors and Destructors
public BoolToVisibilityConverter()
{
this.TrueValue = Visibility.Visible;
this.FalseValue = Visibility.Collapsed;
}
#endregion
}
/// <summary>
/// Use as the base class for BoolToXXX style converters
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class BoolToValueConverter<T> : MarkupExtension, IValueConverter
{
#region Constructors and Destructors
protected BoolToValueConverter()
{
this.TrueValue = default(T);
this.FalseValue = default(T);
}
#endregion
#region Public Properties
public T FalseValue { get; set; }
public T TrueValue { get; set; }
#endregion
#region Public Methods and Operators
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return System.Convert.ToBoolean(value) ? this.TrueValue : this.FalseValue;
}
// Override if necessary
public virtual object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return value.Equals(this.TrueValue);
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
#endregion
}