【发布时间】:2011-02-18 17:04:48
【问题描述】:
在 Windows 窗体应用程序中,触发 INotifyPropertyChanged 的属性更改将导致窗体从我的绑定对象中读取每个属性,而不仅仅是属性更改。 (见下面的示例代码)
这似乎很浪费,因为接口需要更改属性的名称。它在我的应用程序中造成大量时钟,因为某些属性获取器需要执行计算。
如果没有更好的方法,我可能需要在我的 getter 中实现某种逻辑来丢弃不必要的读取。
我错过了什么吗?有没有更好的办法?请不要说要使用不同的演示技术——我在 Windows Mobile 上这样做(尽管这种行为也发生在整个框架上)。
这里有一些玩具代码来演示这个问题。单击该按钮将导致两个文本框都被填充,即使其中一个属性已更改。
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace Example
{
public class ExView : Form
{
private Presenter _presenter = new Presenter();
public ExView()
{
this.MinimizeBox = false;
TextBox txt1 = new TextBox();
txt1.Parent = this;
txt1.Location = new Point(1, 1);
txt1.Width = this.ClientSize.Width - 10;
txt1.DataBindings.Add("Text", _presenter, "SomeText1");
TextBox txt2 = new TextBox();
txt2.Parent = this;
txt2.Location = new Point(1, 40);
txt2.Width = this.ClientSize.Width - 10;
txt2.DataBindings.Add("Text", _presenter, "SomeText2");
Button but = new Button();
but.Parent = this;
but.Location = new Point(1, 80);
but.Click +=new EventHandler(but_Click);
}
void but_Click(object sender, EventArgs e)
{
_presenter.SomeText1 = "some text 1";
}
}
public class Presenter : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _SomeText1 = string.Empty;
public string SomeText1
{
get
{
return _SomeText1;
}
set
{
_SomeText1 = value;
_SomeText2 = value; // <-- To demonstrate that both properties are read
OnPropertyChanged("SomeText1");
}
}
private string _SomeText2 = string.Empty;
public string SomeText2
{
get
{
return _SomeText2;
}
set
{
_SomeText2 = value;
OnPropertyChanged("SomeText2");
}
}
private void OnPropertyChanged(string PropertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(PropertyName));
}
}
}
}
【问题讨论】:
标签: c# .net winforms data-binding inotifypropertychanged