如何刷新Windows窗体控件的简单绑定?

时间:2021-07-08 15:54:53

I'm binding a domain objects property to the Text property of a System.Windows.Forms.Label using the DataBindings:

我正在使用DataBindings将域对象属性绑定到System.Windows.Forms.Label的Text属性:

Label l = new Label();
l.DataBindings.Add(new Binding("Text",myDomainObject,"MyProperty"));

However, when I change the domain object, the Label does not reflect the change. I know that for complex Controls like the DataGridView, binding can be done with a BindingSource on which I can call ResetBindings, but I couldn't find any method to update the binding in the simple case of a Label.

但是,当我更改域对象时,Label不会反映更改。我知道对于像DataGridView这样的复杂控件,可以使用BindingSource完成绑定,我可以在其上调用ResetBindings,但是在Label的简单情况下我找不到任何更新绑定的方法。

2 个解决方案

#1


Your domain object should implement INotifyPropertyChanged so that the binding knows when the underlying property has changed.

您的域对象应实现INotifyPropertyChanged,以便绑定知道底层属性何时发生更改。

#2


Kent has the correct answer, but I want to add a little tidbit on applying INotifyPropertyChanged interface.

Kent有正确的答案,但我想在应用INotifyPropertyChanged界面时添加一点点花絮。

To raise the event easily try this

要轻松举起活动,请尝试这样做

protected void OnPropertyChanged<T>(Expression<Func<T>> property)
{
    if (this.PropertyChanged != null)
    {
        var mex = property.Body as MemberExpression;
        string name = mex.Member.Name;
        this.PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

and apply it like

并应用它

{ // inside some method or property setter
    OnPropertyChanged(() => this.MyProperty);
}

The only reason this is better than specifying the property by name, is that if you refactor, or just change the name of the property you won't have to manually change the implentation, but can let the compiler rename all the references automatically.

这比通过名称指定属性更好的唯一原因是,如果您重构,或者只是更改属性的名称,则不必手动更改实现,但可以让编译器自动重命名所有引用。

#1


Your domain object should implement INotifyPropertyChanged so that the binding knows when the underlying property has changed.

您的域对象应实现INotifyPropertyChanged,以便绑定知道底层属性何时发生更改。

#2


Kent has the correct answer, but I want to add a little tidbit on applying INotifyPropertyChanged interface.

Kent有正确的答案,但我想在应用INotifyPropertyChanged界面时添加一点点花絮。

To raise the event easily try this

要轻松举起活动,请尝试这样做

protected void OnPropertyChanged<T>(Expression<Func<T>> property)
{
    if (this.PropertyChanged != null)
    {
        var mex = property.Body as MemberExpression;
        string name = mex.Member.Name;
        this.PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

and apply it like

并应用它

{ // inside some method or property setter
    OnPropertyChanged(() => this.MyProperty);
}

The only reason this is better than specifying the property by name, is that if you refactor, or just change the name of the property you won't have to manually change the implentation, but can let the compiler rename all the references automatically.

这比通过名称指定属性更好的唯一原因是,如果您重构,或者只是更改属性的名称,则不必手动更改实现,但可以让编译器自动重命名所有引用。