>我有相当有趣的问题。我在 wpf 中有一个数据网格,如下所示:
<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");
}
如您所见,我尝试在添加命令中刷新视图,但它不起作用。有什么建议吗?
绑定到表彰视图:
<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