WPF DataGrid.ItemSsource

时间:2009-06-11 16:00:26

标签: wpf datagrid datagridview

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

3 个答案:

答案 0 :(得分:3)

您需要绑定到实现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更容易实现,因此您可能也想要阅读它。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

如果由于某种原因无法使用ObservableCollection,您也可以使用实现INotifyCollectionChanged接口的集合...

相关问题