我正在尝试从 ListBox 中删除一个项目。该命令已正确触发,并且该项目已从数据库中正确删除,但未刷新列表。
这是视图模型。我正在使用 MVVM Light 4.1
public class ViewAllViewModel : ViewModelBase
{
public ViewAllViewModel()
{
NavigateToAddNew = new RelayCommand(() => NavigationController<Views>.Current.NavigateTo(Views.AddNew));
Remove = new RelayCommand<int>(DeleteMeasure);
using (var repository = App.ServiceLocator.Get<IRepository>())
{
Measures = new ObservableCollection<Measure>(repository.Measures);
}
}
private void DeleteMeasure(int measureId)
{
Measure measure;
using (IRepository repository = App.ServiceLocator.Get<IRepository>())
{
measure = repository.Measures.Single(m => m.Id == measureId);
repository.Measures.Delete(measure);
repository.SaveChanges();
}
measure = Measures.Single(m => m.Id == measureId);
if (Measures.Remove(measure))
{
RaisePropertyChanged(() => Measures);
}
}
public RelayCommand NavigateToAddNew { get; set; }
public RelayCommand<int> Remove { get; set; }
private ObservableCollection<Measure> _measures;
public ObservableCollection<Measure> Measures
{
get { return _measures; }
set { Set(() => Measures, ref _measures, value); }
}
}
谢谢您的帮助。
PS:我知道有类似的问题,但没有一个被接受的答案对我有用:(
编辑 1 这是我在 XAML 页面中用于将 ListBox 绑定到项目列表的代码:
<ListBox Grid.Row="1" DataContext="{Binding Path=Measures}" ItemsSource="{Binding}" />
这是 ViewModel 到主容器的绑定
<Grid DataContext="{Binding Source={StaticResource Locator}, Path=ViewAll}" x:Name="LayoutRoot" />
编辑 2 这是 ViewModel 的完整代码
public class ViewAllViewModel : ViewModelBase
{
public ViewAllViewModel()
{
NavigateToAddNew = new RelayCommand(() => NavigationController<Views>.Current.NavigateTo(Views.AddNew));
Remove = new RelayCommand<int>(DeleteMeasure);
LoadMeasures();
Messenger.Default.Register<PropertyChangedMessage<ObservableCollection<Measure>>>(this, message => LoadMeasures());
}
private void LoadMeasures()
{
using (var repository = App.ServiceLocator.Get<IRepository>())
{
Measures = new ObservableCollection<Measure>(repository.Measures.OrderByDescending(m => m.MeasureDate).ThenByDescending(m => m.Id).Take(20));
}
}
private void DeleteMeasure(int measureId)
{
Measure measure;
using (IRepository repository = App.ServiceLocator.Get<IRepository>())
{
measure = repository.Measures.Single(m => m.Id == measureId);
repository.Measures.Delete(measure);
repository.SaveChanges();
}
measure = Measures.Single(m => m.Id == measureId);
Measures.Remove(measure);
RaisePropertyChanged("LastMeasure", null, measure, true);
}
public RelayCommand NavigateToAddNew { get; set; }
public RelayCommand<int> Remove { get; set; }
private ObservableCollection<Measure> _measures;
public ObservableCollection<Measure> Measures
{
get { return _measures; }
set { Set(() => Measures, ref _measures, value); }
}
}