【发布时间】:2017-08-31 09:56:23
【问题描述】:
我有一个DataGrid,它绑定到ViewModel 中的ObservableCollection。这是搜索结果DataGrid。问题是在我更新搜索结果ObservableCollection 后,实际的DataGrid 没有更新。
在我投反对票之前,请注意这不是关于列中的数据(绑定完美)它是关于清除然后放置全新的数据到ObservableCollection 中,不会更新DataGrid。 So linking to something like this will not help as my properties are working correctly
背景:
ObservableCollection 像这样在ViewModel 中声明;
public ObservableCollection<MyData> SearchCollection { get; set; }
像这样绑定到我的搜索ObservableCollection的搜索DataGrid;
<DataGrid ItemsSource="{Binding SearchCollection}" />
在ViewModel我有这样的搜索方法;
var results =
from x in MainCollection
where x.ID.Contains(SearchValue)
select x;
SearchCollection = new ObservableCollection<MyData>(results);
该方法正确触发并产生所需的结果。然而,DataGrid 并未使用新结果进行更新。我知道ViewModel 有正确的数据,因为如果我在页面上放置一个按钮并在点击事件中放置此代码;
private void selectPromoButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
var vm = (MyViewModel)DataContext;
MyDataGrid.ItemsSource = vm.SearchCollection;
}
DataGrid 现在可以正确显示结果。
我知道我可以在页面后面的代码中放置一些事件,但这不会打败 MVVM 吗?处理此问题的正确 MVVM 方法是什么?
【问题讨论】: