Binding the bool property to the BackColor property for WinForm

I have Formin my application WinForm, which contains TextBoxthis TextBoxbinding to the property of the FirstNameobject Person.

public class Person
{
   string firstName;
   public string FirstName
   {
      get { return firstName; }
      set { 
           firstName = value; 
           this.isOdd = value.Length % 2;
          }
   }

   bool isOdd;  
   public bool IsOdd { get {return isOdd; } }
}

When my application starts, this one Formshows and the user can enter their name in the TextBox. How to bind a property BackColorof the object Formtagged IsOddobject Personwhen IsOdd True BackColorset to Color.Green, and when it Falseis installed BackColoron Color.Red)?

+4
source share
2 answers

Binding winforms wpf. wpf Converter winforms Format. :

Binding bind = new Binding("BackColor", person, "IsOdd");
bind.Format += (s, e) => {
   e.Value = (bool)e.Value ? Color.Green : Color.Red;
};
control.DataBindings.Add(bind);

Person . winforms , EventNameChanged OnEventNameChanged. , winforms. INotifyPropertyChanged, wpf. :

public class Person {
  string firstName;
  public string FirstName {
     get { return firstName; }
     set {
           firstName = value;
           IsOdd = value.Length % 2 != 0;//Note use IsOdd not isOdd
         }
  }
  bool isOdd;
  public bool IsOdd {
    get { return isOdd; }
    private set { 
         if(isOdd != value){
           isOdd = value;
           OnIsOddChanged(EventArgs.Empty);
         }
    }
    public event EventHandler IsOddChanged;
    protected virtual void OnIsOddChanged(EventArgs e) {
      var handler = IsOddChanged;
      if (handler != null) handler(this, e);
    }        
}

. private set, IsOdd , IsOdd . !.

+6

Color bool, - . readonly Color .

internal class MyClass : INotifyPropertyChanged
{
    private bool _isOdd;
    public bool IsOdd 
    {
        get
        {
            return _isOdd;
        }
        set
        {
            _isOdd = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("IsOdd"));
                PropertyChanged(this, new PropertyChangedEventArgs("Color"));
            }
        }
    }

    public Color Color
    {
        get
        {
            return (IsOdd) ? Color.Green : Color.Red;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

BackColor .

control.DataBindings.Add("BackColor", myclass, "Color");

: INotifyPropertyChanged , , , .

+1

All Articles