1
Winforms有兩個文本框。 textBox2
綁定到屬性Unit。 我希望對單元或textBox2
所作的任何更改將分別自動更新textBox2
或單元。但事實並非如此。 這是Winform的三個版本的代碼。Winforms帶雙向DataBinding的文本框不能正常工作
版本一個組數據綁定,希望這將有兩種方式自動更新,但不工作
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
然後進行更新。那麼該怎麼做呢?