1
如果我更改當前集中文本框的數據綁定對象,文本框不會顯示新值。更改綁定對象時不會更新文本框集中
給定一個帶有按鈕,標籤和文本框的簡單表單,請使用下面的代碼。如果用戶更改了文本框的值和製表符,則不會重置文本以匹配新綁定的值(本例中爲20)。但是,如果我通過按鈕單擊事件觸發更新,文本框更新正常。
當屬性更改事件在此處觸發時,如何獲取文本框的值以顯示新綁定的值(20)?
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace BindingsUpdate
{
public partial class Form1 : Form
{
private MyData _data;
private System.Windows.Forms.BindingSource myDataBindingSource;
public Form1()
{
InitializeComponent();
this.components = new System.ComponentModel.Container();
this.myDataBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.myDataBindingSource.DataSource = typeof(BindingsUpdate.MyData);
this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.myDataBindingSource, "Value", true));
this.label1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.myDataBindingSource, "Value", true));
_data = new MyData() { Value = 10.0};
this.myDataBindingSource.DataSource = _data;
_data.PropertyChanged += Data_PropertyChanged;
}
private void Data_PropertyChanged (object sender, PropertyChangedEventArgs e)
{
RefreshData();
}
private void RefreshData()
{
_data.PropertyChanged -= Data_PropertyChanged;
_data = new MyData() {Value = 20.0};
this.myDataBindingSource.DataSource = _data;
//these don't seem to do anything..
this.myDataBindingSource.ResetBindings(false);
this.myDataBindingSource.ResetCurrentItem();
_data.PropertyChanged += Data_PropertyChanged;
}
private void button1_Click(object sender, EventArgs e)
{
RefreshData();
}
}
public class MyData : INotifyPropertyChanged
{
private double _value;
public double Value
{
get { return _value; }
set
{
if (value.Equals(_value)) return;
_value = value;
OnPropertyChanged("Value");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
這工作的感謝。我希望BindingSource.ResetBindings會爲我做這個。在我的應用程序中,我將不得不手動清除屏幕上的所有文本框,這很痛苦。 – kbeal2k 2014-08-28 14:37:07
@ kbeal2k我認爲不斷改變這樣的數據源是不常見的。您可能想重新考慮該策略。 – LarsTech 2014-08-28 14:46:54
即使我直接更改_data.Value並且不更改數據源,也會出現此問題。 – kbeal2k 2014-08-28 19:06:10