2014-01-13 71 views
0

我是WPF的新手,有點迷路。文本和前景色綁定標籤

我想一個標籤綁定到下面的類中顯示的文本:

class Status 
{ 
    public string Message; 
    public bool Success; 
} 

我想,如果成功的標籤顯示爲綠色的「消息」,並以紅色如果沒有。我不知道如何開始。

回答

1

首先,您需要綁定到屬性,而不是成員。你還應該養成在你的課堂上實施INotifyPropertyChanged的習慣。

public class Status : INotifyPropertyChanged 
{ 
    private string message; 
    public string Message 
    { 
     get { return this.message; } 
     set 
     { 
      if (this.message == value) 
       return; 

      this.message = value; 
      this.OnPropertyChanged("Message"); 
     } 
    } 

    private bool success; 
    public bool Success 
    { 
     get { return this.success; } 
     set 
     { 
      if (this.success == value) 
       return; 

      this.success = value; 
      this.OnPropertyChanged("Success"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected void OnPropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

在約束力的條款,你就必須使用自定義IValueConverter

public class RGColorConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (value == null) 
      return null; 

     bool success = (bool) value; 
     return success ? Brushes.Green : Brushes.Red; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

和有關裝訂/設置

<Window.Resources> 
    <wpfApplication2:RGColorConverter x:Key="colorConverter" /> 
</Window.Resources> 

<Label Content="{Binding Message}" Foreground="{Binding Success, Converter={StaticResource colorConverter}}" /> 
+0

大。感謝您的詳細解答。 – Padmaja