使用 ViewModel class 的不同实例会导致更新 ObservableCollection 时出现问题?

Using different instances of a ViewModel class can cause problems updating an ObservableCollection?

我有一个 BookViewModel class 有一些属性,其中之一是 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 中,我这样做:

private TrainViewModel booksViewModel;
// ...
booksViewModel = new BookViewModel(booksList);  // booksList comes from other site
this.DataContext = this.booksViewModel;

在另一个 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,但在每个视图中使用不同的实例(new 事情)是否会导致问题。

好的,我可以解决它。不确定我是否表达得很好,但就像我在修改不同的数据源(即数据上下文)一样。所以,我所做的是尝试将子 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 概念)。