将UI元素与实体绑定

时间:2014-02-13 03:43:44

标签: c# winforms

我有一个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();
}

1 个答案:

答案 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();
}
相关问题