通过MVVM中的属性更改其他类的属性吗?

问题描述 投票:0回答:1

我以前相似的question通过使用INotifyPropertyChanged来回答。但是,研究告诉我,从ViewModelBase继承GalaSoft.MvvmLightINotifyPropertyChanged类似。

我从问题中使用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时一样工作。

c# mvvm mvvm-light
1个回答
1
投票

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

您实际上可以从INotifyPropertyChanged类(请参阅Fruit)中删除previous question的继承,因为只要在类PropertyChangedEventHandler中使用System.ComponentModel,您仍然可以使用usings

因此,基本上,这是对上一个问题的答案的唯一更改:

public class Fruit : ViewModelBase
{
    ....
}
© www.soinside.com 2019 - 2024. All rights reserved.