数据绑定和控件

5
我们的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对象相关联的所有控件。
任何帮助都将不胜感激。
2个回答

2

这就是如何完成的。

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;

0

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


我已经实现了INotifyPropertyChange。谢谢。我认为我需要使用DataBindings.Add(...)。 - user90150

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接