【问题标题】:Data Binding and controls数据绑定和控件
【发布时间】:2011-01-04 14:00:05
【问题描述】:

我们要在我们的 WinForms 应用程序中的控件上执行以下操作。

public class BindableDataItem
{
   public bool Visible {get; set; }
   public bool Enabled {get;set;}

}

现在我们要将 BindableDataItem 绑定到一个文本框。

这里是绑定关联。

TextBox.Enabled BindableDataItem.Enabled

TextBox.Visible BindableDataItem.Visible

现在一个 BindableDataItem 对象可能与许多不同类型的控件相关联。

通过调用 (BindableDataItem) obj.Enabled = false 应该禁用所有附加到 BindableDataItem 对象的控件。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# .net winforms data-binding


    【解决方案1】:

    这是怎么做的

    class MyDataSouce : INotifyPropertyChanged 
    {
        public event PropertyChangedEventHandler PropertyChanged = delegate { };
    
        private bool enabled=true, visible=true;
    
        public bool Enabled {
            get { return enabled; }
            set {
                enabled= value;
                PropertyChanged(this, new PropertyChangedEventArgs("Enabled"));
            }
    
        }
    
        public bool Visible {
            get { return visible; }
            set {
                visible = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Visible"));
            }
        }
    }
    

    现在将表单中的控件绑定到数据源。

    MyDataSouce dataSource = new MyDataSouce();
    foreach (Control ctl in this.Controls) {
    
        ctl.DataBindings.Add(new Binding("Enabled", dataSource, "Enabled"));
        ctl.DataBindings.Add(new Binding("Visible", dataSource, "Visible"));
    
    }
    

    现在您可以启用/禁用控件,例如

    dataSource.Enabled = false;
    

    【讨论】:

      【解决方案2】:

      为了使绑定起作用,这个 BindableDataItem 必须实现 INotifyPropertyChange 接口。 你这样做了吗?

      【讨论】:

      • 我已经实现了 INotifyPropertyChange。谢谢。我想,我必须使用 DataBindings.Add(...)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      相关资源
      最近更新 更多