我正在通过DataGrid.ItemSource属性将IEnumerable集合传递给WPF DataGrid。但是当我试图更改代码中的集合项时,它不会更新DataGrid。为什么?
发布于 2009-06-11 16:01:47
您需要绑定到实现INotifyCollectionChanged接口的类型,以便它提供数据绑定可以用来监视何时添加或删除项的事件。在WPF中,最好的类型是ObservableCollection<>,它有一个可以接受IEnumerable的构造函数:
ObservableCollection<string> collection = new ObservableCollection<string>(iEnumerableobject);
dataGrid.ItemSource = collection;
collection.Add("Wibble");将正确更新。
从您对另一个答案的评论中,看起来您需要从UI线程内部调用add调用。如果不了解您的代码的更多细节,我不知道您为什么需要这样做,但让我们假设您正在从后台的服务中获取数据:
private ObservableCollection<string> collection;
public void SetupBindings()
{
collection = new ObservableCollection<string>(iEnumerableobject);
dataGrid.ItemSource = collection;
//off the top of my head, so I may have this line wrong
ThreadPool.Queue(new ThreadWorkerItem(GetDataFromService));
}
public void GetDataFromService(object o)
{
string newValue = _service.GetData();
//if you try a call add here you will throw an exception
//because you are not in the same thread that created the control
//collection.Add(newValue);
//instead you need to invoke on the Ui dispatcher
if(Dispather.CurrentDispatcher.Thread != Thread.CurrentThread)
{
Dispatcher.CurrentDispatcher.Invoke(() => AddValue(newValue));
}
}
public void AddValue(string value)
{
//because this method was called through the dispatcher we can now add the item
collection.Add(value);
}正如我所说的,我手头没有IDE,所以这可能无法编译,但会为您指明正确的方向。
不过,根据您在后台执行的确切任务,可能有更好的方法来完成此任务。我上面的例子使用backgroundworker实现要容易得多,所以你可能也想读一读这方面的内容。
发布于 2009-06-11 16:02:31
您需要改用ObservableCollection。(或者让您自己的类包装集合并实现INotifyPropertyChanged接口)
发布于 2010-09-20 09:58:33
如果由于某些原因不能使用INotifyCollectionChanged,也可以使用实现ObservableCollection接口的集合。
https://stackoverflow.com/questions/981999
复制相似问题