【问题标题】:How to refresh a simple binding of a Windows Forms control?如何刷新 Windows 窗体控件的简单绑定?
【发布时间】:2009-01-04 18:38:09
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# .net binding


    【解决方案1】:

    Kent 有正确答案,但是我想补充一点关于应用INotifyPropertyChanged 接口的花絮。

    要轻松引发事件,试试这个

    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));
        }
    }
    

    并像这样应用它

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2010-12-02
        • 2013-04-11
        • 1970-01-01
        • 2012-12-17
        • 2018-12-05
        • 1970-01-01
        • 1970-01-01
        • 2016-05-23
        • 1970-01-01
        相关资源
        最近更新 更多