代码之家  ›  专栏  ›  技术社区  ›  iLemming

wpf数据报.itemsource

  •  0
  • iLemming  · 技术社区  · 15 年前

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

    3 回复  |  直到 13 年前
        1
  •  3
  •   Martin Harris    15 年前

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

    ObservableCollection<string> collection = new ObservableCollection<string>(iEnumerableobject);
    dataGrid.ItemSource = collection;
    collection.Add("Wibble");
    

    将正确更新。


    从您的注释到另一个答案,您似乎需要从UI线程内部调用添加调用。在不了解您的代码的情况下,我不知道您为什么需要这样做,但假设您是从后台的服务获取数据:

    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 ,所以你也可以读一下。

        2
  •  1
  •   Simon P Stevens    15 年前

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

        3
  •  0
  •   iLemming    14 年前

    如果出于某种原因不能使用ObservableCollection,也可以使用实现inotifyCollectionChanged接口的集合…