2017-01-13 135 views
1

我有一個相當有趣的問題。我有一個DataGrid的WPF看起來像:使用WPF MVVM中的ICollectionView更新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"); 
    } 

正如你看到我試圖刷新視圖中添加的命令,但沒有奏效。有什麼建議麼?

+0

您已將DataGrid的ItemsSource屬性綁定到名爲「View」的屬性,但您正在刷新一些名爲「Co」的屬性mmendationView」。您應該刷新DataGrid綁定的相同視圖。 – mm8

回答

1

綁定到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