我有一个winforms应用程序,我想要实现的是,一旦绑定到的对象被更改,User Interface面会自动更新它。
这是我试过的,但不幸的是文本框文本没有自动更改!
Employee employee = new Employee();
public Form1()
{
InitializeComponent();
textBox1.DataBindings.DefaultDataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged;
textBox1.DataBindings.Add("Text", employee, "Name");
}
class Employee
{
public string Name { get; set; }
public int Age { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
employee.Name = Guid.NewGuid().ToString();
}
答案 0 :(得分:0)
在button1_Click
中设置员工姓名后,您可以通过调用textBox1
方法更新ReadValue
'Text属性来强制textBox1
重新读取绑定值。< / p>
textBox1.DataBindings[0].ReadValue();
或者,您可以将依赖的员工实例变为BindingSource
,并在button1_Click
中重置BindingSource。
Employee employee = new Employee();
BindingSource source;
public Form1()
{
InitializeComponent();
source = new BindingSource();
source.DataSource = employee;
textBox1.DataBindings.Add("Text", source, "Name");
}
private void button1_Click(object sender, EventArgs e)
{
employee.Name = Guid.NewGuid().ToString();
source.ResetCurrentItem();
}