Winforms DataBinding是否适用于程序更改的属性?

Joa*_*nge 3 .net c# data-binding winforms

我有一些使用DataBindings.Add方法的UI控件,如果我手动更改指定的UI属性,或者源对象在外部更改,它可以工作.

但是如果我在代码中调用UI.Property = value,那么它不会更改UI,也不会更改为DataBindings.Add指定的源对象.

我究竟做错了什么?我使用不正确吗?

Nic*_*cki 9

除非对象实现,否则控件将不知道任何内容已更改INotifyPropertyChanged.然后,更改对象中的属性设置器以引发PropertyChanged事件,传入事件参数中更改的属性的名称.

INotifyPropertyChanged是一个特殊的接口,WinForms中的数据绑定机制在连接数据绑定时查找.如果它看到一个实现该接口的对象,它将订阅它的事件,你会看到你的UI自动刷新,而不必告诉数据绑定器重新读取它们的值(如果你重新分配它会发生什么)DataSource等).

不明显,但是当你想到它时就有意义了.如果没有广播事件,UI控件将如何知道该属性已更改?它不是经常对房产进行投票.它必须被告知财产已经改变,PropertyChanged事件是传统方式.

像(未编译的代码)......


public class MyInterestingObject : INotifyPropertyChanged
{
    private int myInterestingInt;

    public event PropertyChangedEventHandler PropertyChanged;

    public int MyInterestingInt
    {
       get { return this.myInterestingInt; }
       set
       {
           if (value != this.myInterestingInt)
           {
               this.myInterestingInt = value;
               this.RaisePropertyChanged("MyInterestingInt");
           }
       }
    }

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

现在,任何具有该对象MyInterestingInt属性数据绑定的代码都会在该属性更改时自行更新.(有些人喜欢用代理为他们实现这个接口.)

警告:确保在举起PropertyChanged活动之前设置更新的值!它很容易做到,并且可能让您不知道为什么价值没有更新.