C# 将复选框.Checked属性绑定到数据集上的属性
环境:Visual Studio 2010、.NET 4.0、WinForms 我有一个C# 将复选框.Checked属性绑定到数据集上的属性,c#,winforms,data-binding,C#,Winforms,Data Binding,环境:Visual Studio 2010、.NET 4.0、WinForms 我有一个数据集,它实现了INotifyPropertyChanged,并在数据集上创建了一个bool属性。我正在尝试将一个复选框绑定到该bool属性。当我尝试在设计器中执行此操作时,我看到的是数据集和数据集中的表,而不是属性。我试图手动执行此操作,但收到的错误是找不到该属性。我看到的唯一不同之处是表单上的属性是正在实例化的数据集的超类,但我甚至不知道这会如何影响任何事情。下面是一段代码片段 派生类定义 属性定义 执行
数据集
,它实现了INotifyPropertyChanged
,并在数据集
上创建了一个bool
属性。我正在尝试将一个复选框绑定到该bool
属性。当我尝试在设计器中执行此操作时,我看到的是数据集
和数据集
中的表,而不是属性。我试图手动执行此操作,但收到的错误是找不到该属性。我看到的唯一不同之处是表单上的属性是正在实例化的数据集
的超类,但我甚至不知道这会如何影响任何事情。下面是一段代码片段
派生类定义
属性定义
执行器
想法?问题直接来自您希望使用衍生数据集类的方式。由于它是数据集
,任何绑定都将使用其默认值,这将进一步“推”绑定到表
绑定
当您绑定到DerivedDataSet
MainFile
属性时,在后台执行的操作是尝试绑定到dataset表中名为MainFile
的表。当然,这会失败,除非数据集中确实有这样的表。出于同样的原因,您不能绑定到baseDataSet
的任何其他属性-例如,或者-它还检查这些表是否存在,而不是属性
这个问题的解决方案是什么?您可以尝试实现不同的DataViewManager
——但是我无法找到关于该主题的可靠资源
我建议为main文件
属性和相关的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);
要绑定数据集中表中的数据,需要绑定到derivedDataSetRapper
dataset
属性,然后浏览表名和列。例如:
textBox.DataBindings.Add("Text", source, "DataSet.Items.Name");
。。。将绑定到原始\u数据集中的表项
和列名称
,不幸的是,这没有帮助。当表单试图显示时,我得到一个invalidargument异常,在System.Forms的方法CheckBindings中,属性MainFile无法绑定到该异常。@wraith808:是的,我重现了您的问题。它来自于数据集
绑定是如何完成的-检查我的编辑。感谢您提供的信息!我试着使用复选框点击的方法,但考虑到开销和这是一个现有的应用程序的事实,我想这更干净。但我很高兴知道原因和解决办法,而且我并不为我所看到的疯狂
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"));
}
}
}
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);
textBox.DataBindings.Add("Text", source, "DataSet.Items.Name");