在WPF MVVM中使用ICollectionView更新DataGrid

时间:2017-01-13 11:46:29

标签: c# wpf mvvm

我有一个相当有趣的问题。我在wpf中有一个看起来像这样的DataGrid:

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

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

我在视图模型中尝试过简单的c#ops: 读:

    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");
    }

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

1 个答案:

答案 0 :(得分:2)

Bind to CommendationView:

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

...并确保此属性的setter引发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