【问题标题】:Updating DataGrid using ICollectionView in WPF MVVM在 WPF MVVM 中使用 ICollectionView 更新 DataGrid
【发布时间】:2017-01-13 11:46:28
【问题描述】:

我有一个相当有趣的问题。我在 wpf 中有一个 DataGrid,如下所示:

<DataGrid ItemsSource="{Binding View, IsAsync=True, Mode = TwoWay}"
          AutoGenerateColumns="False" 
          EnableColumnVirtualization="True" 
          EnableRowVirtualization="True"
          VirtualizingStackPanel.VirtualizationMode="Standard"
          VirtualizingStackPanel.IsVirtualizing="True">
     COLUMNS
</DataGrid>

在该网格中的数据上,我正在执行 crud 操作,但似乎在添加或删除操作后我无法刷新视图,当我更新记录或过滤它时它工作得很好。

我在视图模型中尝试过的简单 C# 操作。

阅读:

    public CommendationViewModel()
    {
        this._catalog = new CatalogContexct();
        this._commendations = this._catalog.Commendations.ToList();

        var commendation = new ListCollectionView(this._commendations);
        this.CommendationView = CollectionViewSource.GetDefaultView(commendation);

        this.AddCommand = new RelyCommand(AddEntity, param => this._canExecute);
        this.EditCommand = new RelyCommand(EditEntity, param => this._canExecute);
        this.UpdateCommand = new RelyCommand(UpdateEntity, param => this._canExecute);
        this.RemoveCommand = new RelyCommand(RemoveEntity, param => this._canExecute);

        this.NameCommand = new RelyCommand(Filter, param => this._canExecute);
        this.CancelCommand = new RelyCommand(Cancel, param => this._canExecute);
    }

并添加:

    public void AddEntity(object obj)
    {
        if(string.IsNullOrEmpty(this.Name))
        {
            MessageBox.Show("Brak nazwy do dodania");
            return;
        }
        var commendation = new Commendation() { Name = this.Name };
        this._catalog.Commendations.Add(commendation);
        this._catalog.SaveChanges();

        var commendationRefresh = new ListCollectionView(this._catalog.Commendations.ToList());
        this.CommendationView = CollectionViewSource.GetDefaultView(commendationRefresh);
        this.CommendationView.Refresh();            

        MessageBox.Show("Nowe źródło polecenia zostało dodane");
    }

如您所见,我尝试在 add 命令中刷新视图,但它不起作用。有什么建议吗?

【问题讨论】:

  • 您已将 DataGrid 的 ItemsSource 属性绑定到名为“View”的属性,但您正在刷新一些名为“CommendationView”的属性。您应该刷新 DataGrid 绑定到的同一视图。

标签: c# wpf mvvm


【解决方案1】:

绑定到 CommendationView:

<DataGrid ItemsSource="{Binding CommendationView}" ...

...并确保该属性的设置器引发 PropertyChanged 事件:

private ICollectionView _commendationView;
public ICollectionView CommendationView
{
    get { return _commendationView; }
    set { _commendationView = value; NotifyPropertyChanged(); }
}

视图模型类必须实现 INotifyPropertyChanged 接口才能工作:https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    相关资源
    最近更新 更多