首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF DataGrid.ItemSource

WPF DataGrid.ItemSource
EN

Stack Overflow用户
提问于 2009-06-11 16:00:26
回答 3查看 3.4K关注 0票数 0

我正在通过DataGrid.ItemSource属性将IEnumerable集合传递给WPF DataGrid。但是当我试图更改代码中的集合项时,它不会更新DataGrid。为什么?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-06-11 16:01:47

您需要绑定到实现INotifyCollectionChanged接口的类型,以便它提供数据绑定可以用来监视何时添加或删除项的事件。在WPF中,最好的类型是ObservableCollection<>,它有一个可以接受IEnumerable的构造函数:

代码语言:javascript
复制
ObservableCollection<string> collection = new ObservableCollection<string>(iEnumerableobject);
dataGrid.ItemSource = collection;
collection.Add("Wibble");

将正确更新。

从您对另一个答案的评论中,看起来您需要从UI线程内部调用add调用。如果不了解您的代码的更多细节,我不知道您为什么需要这样做,但让我们假设您正在从后台的服务中获取数据:

代码语言:javascript
复制
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实现要容易得多,所以你可能也想读一读这方面的内容。

票数 3
EN

Stack Overflow用户

发布于 2009-06-11 16:02:31

您需要改用ObservableCollection。(或者让您自己的类包装集合并实现INotifyPropertyChanged接口)

票数 1
EN

Stack Overflow用户

发布于 2010-09-20 09:58:33

如果由于某些原因不能使用INotifyCollectionChanged,也可以使用实现ObservableCollection接口的集合。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/981999

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档