我的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
}
完美,謝謝 –