Binding
in winforms
also has something very similar to wpf
. In WPF
you have Converter
and yes in winforms
it's supported by an event called Format
. You can try this code:
Binding bind = new Binding("BackColor", person, "IsOdd");
bind.Format += (s, e) => {
e.Value = (bool)e.Value ? Color.Green : Color.Red;
};
control.DataBindings.Add(bind);
For the class Person
, you have to modify it a little. In winforms
there is a pattern to notify changes is by using the event with name EventNameChanged
together with the raiser named OnEventNameChanged
. You can find this pattern is implemented mostly in winforms
. You can also use INotifyPropertyChanged
which is more familiar in WPF
. Here is the modified class:
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);
}
}
NOTE You can use private set
to allow all private code to change the property IsOdd
via the setter and notify the changes correctly, using the private variable isOdd
won't notify changes unless you have to append some notifying code after that. This code is also Tested!.