可观察集合不会更新数据表格。

3

我正在使用一个Dim All_PriceLists As System.Collections.ObjectModel.ObservableCollection(Of BSPLib.PriceLists.PriceListPrime),其中PriceListPrime实现了Inotify以使其所有属性可通知。

我将All_PriceList绑定到一个datagrid上,如下所示:DataGrid1.ItemsSource = All_PriceLists,但是当我执行All_PriceLists=Getall()时,Getall从数据库中读取并获取数据,但datagrid没有更新。

只有在我这样“黑客式”地处理它时,它才会更新:

DataGrid1.ItemsSource = Nothing
DataGrid1.ItemsSource = All_PriceLists

请问您能告诉我哪里出错或者应该怎样实现吗?谢谢。

3个回答

4
您有几种解决方案来解决您的问题。
  • Update the ItemsSource directly (instead of replacing the local member variable)

    DataGrid1.ItemsSource = new ObservableCollection(Of PriceListPrime)(GetAll())
    
  • Update the ObservableCollection (as mentioned in another answer)

    All_PriceList.Clear(); 
    For Each item in Getall() 
        All_PriceList.Add(item) 
    Next 
    
  • Set your DataContext to a view model and bind to a property of the view model

    Dim vm as new MyViewModel()
    DataContext = vm
    vm.Items = new ObservableCollection(Of PriceListPrime)(GetAll())        
    

    The view model will implement INotifyPropertyChanged and raised the PropertyChanged event when the Items property is changed. In the Xaml your DataGrid's ItemsSource will bind to the Items property.


如果我完全使用MyViewModel而不是All_PriceLists,绑定是否能够工作,这样做是否允许我使用查询而无需使用ctype,因为前一个是(of T)类型。它会吗?您是否可以指向提供更多信息的资源。 - surpavan
你需要更多信息的是哪一部分?我猜应该是MVVM和DataContext的使用。在SO上搜索,会有很多资源。 - Phil
这就是MVVM的作用。谢谢,我会尽量多花时间在上面。 - surpavan

2

如果您希望应用程序对您的更改做出反应,应更新ObservableCollection而不是创建新的。

因此,请清除All_PriceList集合并向其中添加新项。示例:

All_PriceList.Clear();
For Each item in Getall()
  All_PriceList.Add(item)
Next

ObservableCollection不支持AddRange,因此您必须逐个添加项目或在自己的集合中实现INotifyCollectionChanged


2
问题在于你没有更新集合,而是替换了它,这是不同的。 数据网格仍然绑定到旧列表,并且更新后的数据存储在一个新的非绑定集合中。因此,你并不是找到解决方案,而是将数据网格绑定到新的集合中,这是正确的做法。
如果你想要更自动化的解决方案,应该将数据网格绑定到数据集/数据表,这是完全不同的代码。

如何解决这种情况,ObservableCollection 中是否有一些属性或方法可以使用? - surpavan
你可以按照'invisible'所建议的做,但是你现在的解决方案更简单、更快。 - user694833

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接