绑定一个布尔值属性一个WinForm的背景色属性 [英] Binding a bool property to BackColor Property of a WinForm
问题描述
我有一个表格
在我的的WinForm
应用程序,包含文本框
这文本框
绑定到姓
A 人的财产
对象。
I have a Form
in my WinForm
application, that contains a TextBox
and this TextBox
bind to FirstName
property of a Person
Object.
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; } }
}
在我的应用程序运行时,这个表格
节目,用户可以键入他/她的名字的文本框,我怎样才能绑定背景色
的属性表格
到人的
对象时( ISODD
属性 ISODD
是真
背景色
集到 Color.Green
键,当它是假
的背景色
设置为 Color.Red
)?
When My application runs, this Form
shows and user could types his/her name to the TextBox, How can I bind BackColor
property of the Form
to the IsOdd
Property of Person
object(when IsOdd
is True
BackColor
set to Color.Green
and when it is False
the BackColor
set to Color.Red
)?
推荐答案
绑定
在的WinForms
也有一些非常类似于 WPF
。在 WPF
已转换
和是在的WinForms
这是支持由称为事件格式
。你可以试试这个code:
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);
对于类人
,你必须修改它一点。在的WinForms
有通知的变化模式是通过一个名为事件 EventNameChanged
与名为募集<$在一起C $ C> OnEventNameChanged 。你可以找到这个模式在的WinForms
实施大多。您还可以使用 INotifyPropertyChanged的
这是 WPF
更熟悉。下面是修改后的类:
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);
}
}
注意您可以使用私人组
来让所有私人code更改的属性 ISODD
通过setter和,除非你有追加后,一些通知code正确通知修改,使用私有变量 ISODD
不会更改通知。这code也是测试!
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!.
这篇关于绑定一个布尔值属性一个WinForm的背景色属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!