我有一个 DataGrid
,它绑定(bind)到 ViewModel
中的一个 ObservableCollection
。这是一个搜索结果DataGrid
。问题是,在我更新搜索结果 ObservableCollection
之后,实际的 DataGrid
没有更新。
在我投反对票之前,请注意这不是关于列中的数据(绑定(bind)工作完美)它是关于清除然后放置全新的数据到不更新 DataGrid
的 ObservableCollection
。 So linking to something like this will not help as my properties are working correctly
背景:
ObservableCollection
在 ViewModel
中声明如下;
public ObservableCollection<MyData> SearchCollection { get; set; }
像这样绑定(bind)到我的搜索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 方法是什么?
最佳答案
尝试在您的模型 View 中实现 INotifyPropertyChanged
例子:
public abstract class ViewModelBase : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
{
var handler = PropertyChanged;
handler?.Invoke(this, args);
}
}
public class YourViewModel : ViewModelBase {
private ObservableCollection<MyData> _searchCollection ;
public ObservableCollection<MyData> SearchCollection
{
get { return _searchCollection; }
set { _searchCollection = value; OnPropertyChanged("SearchCollection"); }
}
}
关于c# - WPF ObservableCollection 在创建新的 ObservableCollection 时不更新 DataGrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43237054/