【问题标题】:WPF ObservableCollection not updating DataGrid when creating a new ObservableCollection创建新的 ObservableCollection 时 WPF ObservableCollection 不更新 DataGrid
【发布时间】:2017-08-31 09:56:23
【问题描述】:

我有一个DataGrid,它绑定到ViewModel 中的ObservableCollection。这是搜索结果DataGrid。问题是在我更新搜索结果ObservableCollection 后,实际的DataGrid 没有更新。

在我投反对票之前,请注意这不是关于列中的数据(绑定完美)它是关于清除然后放置全新的数据到ObservableCollection 中,不会更新DataGridSo 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 方法是什么?

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    尝试在你的模型视图中实现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"); }
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      问题是您正在重置 SearchCollection 属性而不是更新集合。当添加、删除或更新列表中的项目时,可观察集合会引发正确的更改事件。但不是当集合属性本身发生变化时。

      在 SearchCollection 设置器中,您可以触发 PropertyChanged 事件。就像任何其他属性一样,当它发生变化时。还要确保您的 DataGrid ItemsSource 绑定是单向的,而不是一次性的。

      <DataGrid  ItemsSource="{Binding SearchCollection, Mode=OneWay}" />
      

      或者您可以更改集合的成员(清除旧结果并添加新结果)。这也应该像您期望的那样更新 DataGrid。

      从您的代码示例中,我会选择第一个选项。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-26
        • 2014-06-01
        • 1970-01-01
        • 2021-10-20
        • 2014-04-06
        • 1970-01-01
        相关资源
        最近更新 更多