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

tra*_*ler 7 c# data-binding winforms

我使用.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));
        }
    }
Run Code Online (Sandbox Code Playgroud)

每个propertysetter调用:

    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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

典型的Propertysetter:

    public String LocalizationItemId {
        get {
            return _localizationItemId;
        }
        set {
             SetField(ref _localizationItemId, value, "LocalizationItemId");
        }
    }
Run Code Online (Sandbox Code Playgroud)

属性绑定到文本框的方式

        private DerivedEntity derivedEntity
        TextBoxDerivedEntity.DataBindings.Add("Text", derivedEntity, "Probenname");
Run Code Online (Sandbox Code Playgroud)

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

Hai*_*ihi 10

我知道回答为时已晚,但是这个问题可以解决,如果你在绑定应该改变值时设置事件,如果你在属性值改变事件上设置它,你的问题就会得到解决.你可以通过这种方式做到这一点

textBox.DataBindings.Add("textBoxProperty", entity, "entityProperty", true, DataSourceUpdateMode.OnPropertyChanged);
Run Code Online (Sandbox Code Playgroud)


Ryo*_*ogo 8

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

初始化绑定:

var entity;
textBox.DataBindings.Add("textBoxProperty", entity, "entityProperty");
Run Code Online (Sandbox Code Playgroud)

更改TextBox.Text:

textBox.Text = "SOME_VALUE";
Run Code Online (Sandbox Code Playgroud)

手动更新绑定:

textBox.DataBindings["textBoxProperty"].WriteValue();
Run Code Online (Sandbox Code Playgroud)

Binding.WriteValue()从控件读取值并相应地更新实体.您可以在MSDN上阅读有关WriteValue的内容.