C# 使用ViewModel类的不同实例会导致更新ObservableCollection时出现问题吗?
我有一个带有一些属性的C# 使用ViewModel类的不同实例会导致更新ObservableCollection时出现问题吗?,c#,wpf,observablecollection,C#,Wpf,Observablecollection,我有一个带有一些属性的BookViewModel类,然后是一个ObservableCollection。但我在更新它的值时遇到了问题。这就是我的情况: public class BookViewModel : INotifyPropertyChanged { private IEnumerable<Book> booksList; private ObservableCollection<Chapter> selectedCha
BookViewModel
类,然后是一个ObservableCollection
。但我在更新它的值时遇到了问题。这就是我的情况:
public class BookViewModel : INotifyPropertyChanged
{
private IEnumerable<Book> booksList;
private ObservableCollection<Chapter> selectedChapters = new ObservableCollection<Chapter>();
public BookViewModel()
{
}
public BookViewModel(List<Book> booksList)
{
this.BooksList = booksList;
}
// ...
public ObservableCollection<Book> SelectedChapters
{
get
{
return this.selectedChapters;
}
set
{
this.selectedChapters = value;
this.OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
在另一个UserControl中,作为前一个UserControl的子控件动态创建,我执行以下操作:
private TrainViewModel booksViewModel;
// ...
booksViewModel = new BookViewModel();
this.DataContext = this.booksViewModel; // Different constructor
在后一页中,我有一些复选框,可以通过添加或删除元素来修改我的selectedChapters
属性:
// When some checkbox is checked
this.booksViewModel.SelectedChapters.Add(selectedChapter);
// When some checkbox is unchecked
this.booksViewModel.SelectedChapters.Remove(selectedChapter);
如果每次选中或取消选中复选框,我会:
Debug.Print(this.booksViewModel.SelectedChapters.Count()); // Always print out 1!!
我想知道是否使用相同的ViewModel,但每个视图中都有不同的实例(新的
东西)导致了这个问题。好的,我可以解决它。不确定我是否表达得很好,但这就像我在修改不同的数据源(即数据上下文)。因此,我所做的是尝试将子UserControl的数据上下文强制转换为BookViewModel
(它是其父控件的数据上下文),并从中进行操作:
// Inside the event handler for check and uncheck
BookViewModel bookViewModel = this.DataContext as BookViewModel;
// When some checkbox is checked
if (bookViewModel != null){
this.booksViewModel.SelectedChapters.Add(selectedChapter);
}
// When some checkbox is unchecked
if (bookViewModel != null){
this.booksViewModel.SelectedChapters.Remove(selectedChapter);
}
就这些。完美更新。在代码的任何部分(甚至在构造函数中),我都不做任何与数据、文本或视图模型相关的事情。现在,就像我在修改父级的相同数据上下文中的数据一样(如果我的解释不准确,很抱歉,我仍然习惯于WPF概念)。根据您的代码,您可以手动从代码后面的集合中添加和删除项。因为您有视图模型,所以我假设您使用的是MVVM模式。要正确实现此功能,请在视图模型中创建命令,以便向集合中添加项和从集合中删除项。
// Inside the event handler for check and uncheck
BookViewModel bookViewModel = this.DataContext as BookViewModel;
// When some checkbox is checked
if (bookViewModel != null){
this.booksViewModel.SelectedChapters.Add(selectedChapter);
}
// When some checkbox is unchecked
if (bookViewModel != null){
this.booksViewModel.SelectedChapters.Remove(selectedChapter);
}