0
votes

I am new to WPF and am a little lost.

I want to display Text within a label binding it to the following class:

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

I want the label to display the "message" in green if success and in red if not. I am not sure how to start on it.

1

1 Answers

2
votes

First, you need to bind to properties, not members. You should also get into the habit of implementing INotifyPropertyChanged on your class that you're binding to.

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));
    }
}

In terms of binding, you'd have to use a custom 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();
    }
}

And the relevant binding/setup

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

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