2011-05-17 97 views
1

环境:的Visual Studio 2010,.NET 4.0,WinForms的绑定Checkbox.Checked财产财产上的DataSet

我有一个实现INotifyPropertyChanged的一个DataSet,并创造了在DataSet中的布尔属性。我试图绑定一个CheckBox.Checked属性到bool属性。当我尝试在设计器中完成它时,我会看到数据集中的数据集和表格,但不是属性。我试图手动执行该操作,但收到该属性未找到的错误。唯一不同的是,我看到我正在做的是表单上的属性是被实例化的数据集的超类,但我甚至都没有看到这会如何影响任何东西。代码片段如下。

派生类定义

public class DerivedDataSetClass: SuperDataSetClass, INotifyPropertyChanged 
{ 
    private bool _mainFile = false; 
    public bool MainFile 
    { 
    get { return this._mainFile; } 
    set { 
     this._mainFile = value; 
     this.NotifyPropertyChanged("MainFile"); 
    } 
    } 
} 

属性定义

private SuperDataSetClass _dataSet; 
public DerivedDataSetClass DataSet 
{ 
    get { return (DerivedDataSetClass)_dataSet; 
} 

男星

this._DataSet = new DerivedDataSetClass (this); 

this.mainFileBindingSource = new BindingSource(); 
this.mainFileBindingSource.DataSource = typeof(DerivedDataSetClass); 
this.mainFileBindingSource.DataMember = "MainFile"; 

var binding = new Binding("Checked", this.mainFileBindingSource, "MainFile"); 
this.chkMainFile.DataBindings.Add(binding); 

的思考?

回答

1

问题直接来自您想要使用您的方式DerivedDataSetClass。由于它是DataSet,所有已完成的绑定都将使用其默认的DataViewManager,其中“推送”进一步绑定到Tables绑定。

当您绑定到DerivedDataSetMainFile财产,什么被引擎盖下做的是绑定到一个名为数据集表中MainFile表的尝试。当然这会失败,除非你真的在数据集中有这样的表格。出于同样的原因,您不能绑定的任何其他财产的基地DataSet - 例如。 LocaleHasErrors - 它还检查这些表是否存在,而不是属性。

这个问题的解决方案是什么?您可以尝试实施不同的DataViewManager - 但我无法找到有关该主题的可靠资源。

我建议什么是您MainFile属性创建简单的包装类及相关DerivedDataSetClass,像这样的:你的包装

public class DerivedDataSetWrapper : INotifyPropertyChanged 
{ 
    private bool _mainFile; 

    public DerivedDataSetWrapper(DerivedDataSetClass dataSet) 
    { 
     this.DataSet = dataSet; 
    } 

    // I assume no notification will be needed upon DataSet change; 
    // hence auto-property here 
    public DerivedDataSetClass DataSet { get; private set; } 

    public bool MainFile 
    { 
     get { return this._mainFile; } 
     set 
     { 
      this._mainFile = value; 
      this.PropertyChanged(this, new PropertyChangedEventArgs("MainFile")); 
     } 
    } 
} 

现在可以绑定到这两个数据集内的内容(表)以及MainFile类。

var wrapper = new DerivedDataSetWrapper(this._DataSet); 
BindingSource source = new BindingSource { DataSource = wrapper }; 

// to bind to checkbox we essentially bind to Wrapper.MainFile 
checkBox.DataBindings.Add("Checked", source, "MainFile", false, 
    DataSourceUpdateMode.OnPropertyChanged); 

要绑定从数据集中的表中的数据,您需要绑定到DerivedDataSetWrapperDataSet属性,然后通过表名和列导航。例如:

textBox.DataBindings.Add("Text", source, "DataSet.Items.Name"); 

...将绑定到您的原始_DataSet中的表Items和列Name

+0

不幸的是,这并没有帮助。当表单尝试显示时,我得到一个invalidargument异常,该属性MainFile无法绑定到System.Forms的CheckBindings方法中。 – 2011-05-18 04:53:05

+0

@ wraith808:是的,我转载了你的问题。它来自DataSet'绑定完成的事实 - 检查我的编辑。 – 2011-05-18 10:52:26

+0

感谢您的信息!我试图绕过使用CheckBox点击方法,但考虑到开销和事实,这是一个现有的应用程序,我想这是更清洁。但我很高兴知道原因,解决方法,并且我对所看到的并不疯狂。 ;) – 2011-05-18 18:05:23