winforms中的双向数据绑定,在基类中实现的Inotifypropertychanged

时间:2013-10-19 15:20:18

标签: c# winforms data-binding

我使用.Net 3.5,Winforms,Databinding

我有派生类,基类实现了IPropertychanged

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string propertyName) {
        var handler = this.PropertyChanged;
        if (handler != null) {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

每个资产设定者都会调用:

    protected void SetField<T>(ref T field, T value, string propertyName) {
        if (!EqualityComparer<T>.Default.Equals(field, value)) {
            field = value;
            IsDirty = true;
            this.RaisePropertyChanged(propertyName);
        }
    }

典型的Propertysetter:

    public String LocalizationItemId {
        get {
            return _localizationItemId;
        }
        set {
             SetField(ref _localizationItemId, value, "LocalizationItemId");
        }
    }

属性绑定到文本框的方式

        private DerivedEntity derivedEntity
        TextBoxDerivedEntity.DataBindings.Add("Text", derivedEntity, "Probenname");

如果我以编程方式将文本分配给文本框,则文本框不会显示该文本框。但我可以手动编辑文本框。

4 个答案:

答案 0 :(得分:9)

我知道现在回答为时已晚,但是这个问题可以解决,如果您在绑定应该更改值时设置事件,如果您在属性值更改事件上设置它,您的问题将得到解决。你可以这样做

textBox.DataBindings.Add("textBoxProperty", entity, "entityProperty", true, DataSourceUpdateMode.OnPropertyChanged);

答案 1 :(得分:8)

绑定源在TextBox Validated事件上更新。当用户编辑TextBox然后将焦点更改为其他控件时,将调用TextBox验证事件。 由于您正在以编程方式更改TextBox文本,因此TextBox不知道文本已更改,因此未调用验证且未更新绑定,因此您需要手动更新绑定。

初始化绑定:

var entity;
textBox.DataBindings.Add("textBoxProperty", entity, "entityProperty");

更改TextBox.Text:

textBox.Text = "SOME_VALUE";

手动更新绑定:

textBox.DataBindings["textBoxProperty"].WriteValue();

Binding.WriteValue()从控件读取值并相应地更新实体。 您可以在MSDN了解WriteValue。

答案 2 :(得分:1)

订阅者未初始化。即

private DerivedEntity derivedEntity
TextBoxDerivedEntity.DataBindings.Add("Text", derivedEntity, "Probenname");

derivedEntity为空。

初始化它,你会没事的。

答案 3 :(得分:0)

我实现了“INotifyPropertyChanged”,但只在新值与旧值不同时才引发PropertyChanged事件:

public class ProfileModel : INotifyPropertyChanged
{
    private Guid _iD;
    private string _name;
    public event PropertyChangedEventHandler PropertyChanged;

    public Guid ID
    {
        get => _iD;
        set
        {
            if (_iD != value)
            {
                _iD = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ID"));
            }
        }
    }

    public string Name
    {
        get => _name;
        set
        {
            if (_name != value)
            {
                _name = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
            }
        }
    }
}

现在只需绑定控件:

txtProfileID.DataBindings.Clear();
txtProfileID.DataBindings.Add("Text", boundProfile, "ID", true, DataSourceUpdateMode.OnPropertyChanged);