TextBox的数据绑定 [英] Data binding for TextBox

查看:115
本文介绍了TextBox的数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本属性,存储一个类型为Fruit的对象:

I have a basic property that stores an object of type Fruit:

Fruit food;
public Fruit Food
{
    get {return this.food;}
    set
    {
        this.food= value;
        this.RefreshDataBindings();
    }
}

public void RefreshDataBindings()
{
    this.textBox.DataBindings.Clear();
    this.textBox.DataBindings.Add("Text", this.Food, "Name");
}

所以我设置 this.Food 表单外,然后显示在UI中。

So I set this.Food outside the form and then it shows up in the UI.

如果我修改 this.Food 它正确更新。如果我以编程方式修改界面如下:

If I modify this.Food, it updates correctly. If I modify the UI programmatically like:

this.textBox.Text =NewFruit,它不更新this.Food。

this.textBox.Text = "NewFruit", it doesn't update this.Food.

为什么会这样?我还为Fruit.Name实现了 INotifyPropertyChanged ,但仍然相同。

Why could this be? I also implemented INotifyPropertyChanged for Fruit.Name, but still the same.

推荐答案

p>我推荐你实现INotifyPropertyChanged并将你的数据绑定代码更改为:

I Recommend you implement INotifyPropertyChanged and change your databinding code to this:

this.textBox.DataBindings.Add("Text",
                                this.Food,
                                "Name",
                                false,
                                DataSourceUpdateMode.OnPropertyChanged);

这将修复它。

请注意,默认的 DataSourceUpdateMode OnValidation ,所以如果不指定 OnPropertyChanged ,模型对象将不会更新,直到您的验证发生。

Note that the default DataSourceUpdateMode is OnValidation, so if you don't specify OnPropertyChanged, the model object won't be updated until after your validations have occurred.

这篇关于TextBox的数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆