Mas*_*oud 5 c# data-binding binding winforms
我Form在我的WinForm应用程序中有一个包含a TextBox和this TextBox绑定到Object的FirstName属性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; } }
}
Run Code Online (Sandbox Code Playgroud)
当我的应用程序运行时,这个Form节目和用户可以键入他/她的名字的文本框,我如何绑定BackColor的属性Form的IsOdd的属性Person对象(当IsOdd被True BackColor设置为Color.Green当它是False将BackColor设置为Color.Red)?
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);
Run Code Online (Sandbox Code Playgroud)
对于课程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);
}
}
Run Code Online (Sandbox Code Playgroud)
注意您可以使用private set允许所有私有代码IsOdd通过setter 更改属性并正确通知更改,使用私有变量isOdd不会通知更改,除非您必须在此之后附加一些通知代码.这段代码也经过测试!.
| 归档时间: |
|
| 查看次数: |
3167 次 |
| 最近记录: |