Wpf 带文本和前景色的绑定标签

Wpf 带文本和前景色的绑定标签,wpf,label,Wpf,Label,我是WPF的新手,有点迷路了 我想在标签中显示文本,将其绑定到以下类: class Status { public string Message; public bool Success; } 如果成功,我希望标签以绿色显示“消息”,否则以红色显示。我不知道如何开始。首先,您需要绑定到属性,而不是成员。您还应该养成在绑定到的类上实现INotifyPropertyChanged的习惯 public class Status : INotifyPropertyChanged { p

我是WPF的新手,有点迷路了

我想在标签中显示文本,将其绑定到以下类:

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

如果成功,我希望标签以绿色显示“消息”,否则以红色显示。我不知道如何开始。首先,您需要绑定到属性,而不是成员。您还应该养成在绑定到的类上实现
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}}" />

太好了。谢谢你的详细回答。