将复选框.选中属性绑定到数据集上的属性
本文关键字:属性 数据集 绑定 复选框 | 更新日期: 2023-09-27 17:56:50
环境: Visual Studio 2010, .NET 4.0, WinForms
我有一个实现INotifyPropertyChanged
的DataSet
,并在DataSet
上创建了一个bool
属性。 我正在尝试将CheckBox.Checked
属性绑定到该bool
属性。 当我尝试在设计器中执行此操作时,我看到DataSet
和DataSet
中的表,但没有看到属性。 我尝试手动执行此操作,但收到找不到该属性的错误。 我看到我正在做的唯一不同的事情是表单上的属性是正在实例化的DataSet
的超类,但我什至看不出这会如何影响任何事情。 下面是一个代码片段。
派生类定义
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);
思潮?
问题直接来自您想要使用DerivedDataSetClass
的方式。因为它是DataSet
的,任何绑定都将使用它的默认DataViewManager
,它将绑定进一步"推动"到Tables
绑定。
绑定到 DerivedDataSet
MainFile
属性时,后台执行的操作是尝试绑定到数据集表中名为 MainFile
的表。当然,这失败了,除非数据集中确实有这样的表。出于同样的原因,您不能绑定到基本DataSet
的任何其他属性 - 例如。 Locale
或HasErrors
- 它还检查此类表是否存在,而不是属性。
这个问题的解决方案是什么?您可以尝试实现不同的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);
若要绑定数据集中表中的数据,需要绑定到DerivedDataSetWrapper
DataSet
属性,然后在表名称和列之间导航。例如:
textBox.DataBindings.Add("Text", source, "DataSet.Items.Name");
。将绑定到原始_DataSet
中的表Items
和列Name
。