【发布时间】:2011-10-07 21:02:49
【问题描述】:
Winforms 有两个文本框。 textBox2 绑定到属性单元。
我希望对 Unit 或 textBox2 所做的任何更改都会分别自动更新 textBox2 或 Unit。但事实并非如此。
以下是 Winform 代码的三个版本。
版本一设置数据绑定,希望有两种方式自动更新但不起作用
public partial class Receiver : Form, INotifyPropertyChanged
{
private int unit=0;
public int Unit
{
get { return unit; }
set
{
if (value != unit)
{
unit = value;
}
}
}
public Receiver()
{
InitializeComponent();
textBox2.DataBindings.Add("Text", Unit, "Unit");
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//textBox1 change makes Unit change,
//I wish the change will be displayed in textBox2 automatically
Unit = Convert.ToInt32(textBox1.Text);
}
}
第二版带有事件处理程序,硬代码用事件处理程序更新textBox2
但更改textBox2仍然不会自动更新单元
public partial class Receiver : Form, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int unit=0;
public int Unit
{
get { return unit; }
set
{
if (value != unit)
{
unit = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
}
public Receiver()
{
InitializeComponent();
textBox2.DataBindings.Add("Text", this.Unit, "Unit", false,
DataSourceUpdateMode.OnPropertyChanged);
PropertyChanged += new PropertyChangedEventHandler(OnPropertyChanged);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Unit = Convert.ToInt32(textBox1.Text);
}
private void OnPropertyChanged(object sender, EventArgs e)
{
//this actually is hard coded to update textBox2, binding does no help
textBox2.Text = Unit.ToString();
}
}
版本三为什么要使用事件处理程序,我们可以简单地这样做。
public partial class Receiver : Form, INotifyPropertyChanged
{
private int unit=0;
public int Unit
{
get { return unit; }
set
{
if (value != unit)
{
unit = value;
textBox2.text = unit.toString();
}
}
}
public Receiver()
{
InitializeComponent();
textBox2.DataBindings.Add("Text", Unit, "Unit");
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Unit = Convert.ToInt32(textBox1.Text);
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
Unit = Convert.ToInt32(textBox2.Text);
}
}
}
第二版和第三版有问题,对textbox1的任何更改都会导致textbox2的更新。这将导致大量的 CPU 周期。最好的方法是当鼠标焦点离开textBox1 然后进行更新。那么该怎么做呢?
【问题讨论】: