在 MVVM 中更改另一个 class' 属性 through 属性?

Change another class' property through property changed in MVVM?

我之前的类似相关 was answered through using INotifyPropertyChanged. However, researches taught me that inheriting ViewModelBase from GalaSoft.MvvmLightINotifyPropertyChanged 类似。

我使用问题中的 来更改 ObservableCollection 中每个项目的数据。但我不想再使用 INotifyPropertyChanged,因为我已经继承了 ViewModelBase。下面的代码是我从我已经提到的答案中添加的一些代码:

美食class

private bool _isAllSelected = true;

public bool IsAllSelected
{
    get
    {
        return _isAllSelected;
    }
    set
    {
        Set(IsAllSelected, ref _isAllSelected, value);
        // send message to viewmodel
        Messenger.Default.Send(Message.message);
    }
}

视图模型class

// message handler
private void MsgHandler(Message message)
{
    RaisePropertyChanged(SelectAllPropertyName);
}

// the property that change all checkbox of fruits
public const string SelectAllPropertyName = "SelectAll";

public bool SelectAll
{
    set
    {
        bool isAllSelected = Foods.Select(c => c.IsAllSelected).Any();
        foreach (var item in Foods.SelectMany(c => c.Fruits).ToList())
        {
            item.IsSelected = isAllSelected;
        }
    }
}

// receives message function, called at the start
public void Receiver()
{
    Messenger.Default.Register<Message>(this, MsgHandler);
}

这里的问题是这不像以前使用的那样工作 INotifyPropertyChanged

您提到您正在使用 以及这个问题中的 "I don't want use INotifyPropertyChanged anymore since I am already inheriting ViewModelBase"

您实际上可以从 Fruit class 中删除 INotifyPropertyChanged 的继承(参考 ),因为您仍然可以使用 PropertyChangedEventHandler 作为只要您在 class usings.

中使用 System.ComponentModel

所以基本上,这将是您之前问题的答案代码的唯一变化:

public class Fruit : ViewModelBase
{
    ....
}