2014-01-13 47 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