【发布时间】:2013-02-15 00:32:48
【问题描述】:
我希望能够将列表绑定到列表框数据源,并且当列表被修改时,列表框的 UI 会自动更新。 (Winforms 不是 ASP)。 这是一个示例:
private List<Foo> fooList = new List<Foo>();
private void Form1_Load(object sender, EventArgs e)
{
//Add first Foo in fooList
Foo foo1 = new Foo("bar1");
fooList.Add(foo1);
//Bind fooList to the listBox
listBox1.DataSource = fooList;
//I can see bar1 in the listbox as expected
}
private void button1_Click(object sender, EventArgs e)
{
//Add anthoter Foo in fooList
Foo foo2 = new Foo("bar2");
fooList.Add(foo2);
//I expect the listBox UI to be updated thanks to INotifyPropertyChanged, but it's not
}
class Foo : INotifyPropertyChanged
{
private string bar_ ;
public string Bar
{
get { return bar_; }
set
{
bar_ = value;
NotifyPropertyChanged("Bar");
}
}
public Foo(string bar)
{
this.Bar = bar;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public override string ToString()
{
return bar_;
}
}
如果我用BindingList<Foo> fooList = new BindingList<Foo>(); 替换List<Foo> fooList = new List<Foo>();,那么它就可以工作。但我不想改变原来的傻瓜类型。我想要这样的工作:listBox1.DataSource = new BindingList<Foo>(fooList);
编辑:另外,我刚刚从 Ilia Jerebtsov 那里读到 List<T> vs BindingList<T> Advantages/DisAdvantages:“当您将 BindingSource 的 DataSource 设置为 List 时,它会在内部创建一个 BindingList 来包装您的列表”。我认为我的示例只是表明这是不正确的:我的 List 似乎没有在内部包装到 BindingList。
【问题讨论】:
-
List 不会引发任何事件让观察者知道何时更新。观察者是 UI 组件还是充当包装器的另一个列表并不重要。为什么在绑定时反对更改为 BindingList 是您需要做的?
-
我不想将 List 更改为 BindingList,因为它已经在项目中的任何地方用作 List。我将不得不替换每个方法签名,我想避免修改已经稳定的内容。
-
如果将返回类型更改为 IList
会怎样?您仍然有相同数量的重大更改吗?
标签: c# winforms datasource