【发布时间】:2014-12-15 14:31:12
【问题描述】:
我正在尝试做一些相当简单的事情,但对 .Net 感到沮丧:
我只是想要一个 WPF DataGrid,它会在末尾自动添加一个空白行,类似于在 MS Access 或 SQL Management Studio 中的表中输入数据。
我的想法是重写 ObservableCollection:保留一个 newItem 成员,我会在读取 Items 集合时动态添加该成员。像这样的:
// Warning this code doesn't work
public class MyCollection<T> : ObservableCollection<T>
{
private T _newItem;
// there would be a constructor which would initialize _newItem
protected override IList<T> Items
{
get
{
List<T> newItems = new List<T>();
newItems.Add(_newItem);
return base.Items.Union(newItems).ToList();
}
}
}
我的代码有几个问题。首先,您不能覆盖 Items 属性的 getter。它是不可覆盖的。
其次,即使可以,当 DataGrid 绑定到集合时,甚至不会调用该 getter。我认为 GetEnumerator 方法应该在这里被覆盖,但当然也不能被覆盖。
扩展 ObservableCollection 类以实现此功能的最简单方法是什么。在这一点上,看起来我必须自己实现整个事情,而不是从 ObservableCollection 继承。出于显而易见的原因,我反对这个想法。
提前致谢!
【问题讨论】:
-
也许可以从 DataGrid 方面着手。
-
DataGrid 为此有一个build-in feature。
-
如果您使用 mvvm,您的视图模型可以随时向集合中添加一个空白项。无需覆盖任何东西
-
blindmeis,我想你可能是对的。这可能是最简单的方法。谢谢。让它成为一个答案,我会这样标记它。
标签: c# wpf generics datagrid observablecollection