2013-06-25 105 views
0

我在代碼中,我可以設置像一個屬性轉換器:WPF轉換屬性

tabAssumptions.SetBinding(UIElement.VisibilityProperty, new Binding("CurrentPhase.IsWholeScheme") { Converter = new BoolToVisibilityConverter { Inverse = true } }); 

如何設置轉換器的逆屬性在XAML使用時?

回答

10

我的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 
} 
+0

完美,謝謝 –