通过在MVVM中更改的属性来更改另一个类的属性?

时间:2019-09-26 08:00:54

标签: c# mvvm mvvm-light

我以前相似的question通过使用INotifyPropertyChanged得到了回答。但是,研究告诉我,从GalaSoft.MvvmLight继承ViewModelBaseINotifyPropertyChanged相似。

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

食物分类

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);
    }
}

ViewModel类

// 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一样起作用。

1 个答案:

答案 0 :(得分:1)

您已经提到您正在使用the answer from your previous question,还有这个“由于我已经继承了ViewModelBase,所以我不再要使用INotifyPropertyChanged”

实际上,您可以从spring.jpa.properties.javax.persistence.validation.group.pre-remove=com.your_package.MyDeleteGroup 类中删除INotifyPropertyChanged的继承关系(请参阅previous question),因为只要您使用{ Fruit中的{1}}。

因此,基本上,这是您上一个问题的答案代码的唯一变化:

PropertyChangedEventHandler