环境:Visual Studio 2010、.NET 4.0、WinForms
我有一个实现了 INotifyPropertyChanged
的 DataSet
,并且在 DataSet
上创建了一个 bool
属性。我正在尝试将 CheckBox.Checked
属性绑定(bind)到该 bool
属性。当我尝试在设计器中执行此操作时,我看到了 DataSet
和 DataSet
中的表,但没有看到属性。我试图手动执行此操作,但收到未找到该属性的错误。我看到我正在做的唯一不同的事情是表单上的属性是正在实例化的 DataSet
的父类(super class),但我什至看不出这会如何影响任何事情。下面是一段代码。
派生类定义
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;
}
Ctor
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);
想法?
最佳答案
问题直接来自您使用 DerivedDataSetClass
的方式.因为它是 DataSet
,任何完成的绑定(bind)都将使用其默认值 DataViewManager
,“插入”进一步绑定(bind)到 Tables
绑定(bind)。
当您绑定(bind)到您的 DerivedDataSet
时MainFile
属性,幕后所做的是尝试绑定(bind)到名为 MainFile
的表在您的数据集表中。当然这会失败,除非你在数据集中真的有这样的表。出于同样的原因,您不能绑定(bind)到基 DataSet
的任何其他属性 - 例如。 Locale
或 HasErrors
- 它还检查此类表是否存在,而不是属性。
这个问题的解决方案是什么?您可以尝试实现不同的 DataViewManager
- 但是我无法找到有关该主题的可靠资源。
我的建议是为您的 MainFile
创建简单的包装器类属性(property)及相关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"));
}
}
}
现在您可以绑定(bind)到数据集内部内容(表格)以及 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);
要从数据集中的表绑定(bind)数据,您需要绑定(bind)到 DerivedDataSetWrapper
DataSet
属性,然后浏览表名和列。例如:
textBox.DataBindings.Add("Text", source, "DataSet.Items.Name");
... 将绑定(bind)到表 Items
和列 Name
在你原来的_DataSet
.
关于c# - 将 Checkbox.Checked 属性绑定(bind)到 DataSet 上的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6037271/