【发布时间】:2010-03-04 16:25:02
【问题描述】:
我正在尝试在 BindingSource 和 ComboBox 之间进行我认为的简单数据绑定。当我用作 BindingSource 的 DataSource 的类具有作为泛型类的实例的属性时,我遇到了问题。
我有以下通用类:
public class GenericClass<T>
{
public T Code { get; set; }
public string Description { get; set; }
public override string ToString()
{
return Description;
}
}
我有一个具有整数代码的类:
public class IntegerClass : GenericClass<int>
{
// Nothing unique here, for simple test.
}
我也有设置为 BindingSource 的 DataSource 的类:
public class ClassBindingClass : INotifyProperty Changed
{
private int _id;
private IntegerClass _choice;
private string _name;
public int Id
{
get { return _id; }
set
{
_id = value;
OnPropertyChanged("Id");
}
}
public IntegerClass Choice
{
get { return _choice; }
set
{
_choice = value;
OnPropertyChanged("Choice");
}
}
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertName));
}
}
在我的表单上,我创建了一个IntegerClass 的集合,并将我的combobox 的datasource 设置为该集合。 (这部分工作正常,组合框正确显示值。)然后我将combobox 的SelectedValue 绑定设置为BindingSource 的Choice 属性更新OnPropertyChanged.
如果我在组合框中选择一个值时将 IntegerClass 替换为非泛型类,则 BindingSource 的 Choice 属性会发生更改,NotifyPropertyChanged 事件会被触发,并且在我的表单上我可以更新一个标签,上面写着“Choice has changed!”。
当 IntegerClass 是 ClassBindingClass 的一部分时,这将不再起作用,而是我无法导航出组合框,而是获得 FormatException。
我想做的事可能吗?数据绑定可以处理泛型吗?
【问题讨论】:
标签: c# winforms generics data-binding