【问题标题】:Change another class' property through property changed in MVVM?通过 MVVM 中更改的属性更改另一个类的属性?
【发布时间】:2019-09-26 08:00:54
【问题描述】:

我之前类似相关的question 是通过使用INotifyPropertyChanged 回答的。然而,研究告诉我,从GalaSoft.MvvmLight 继承ViewModelBaseINotifyPropertyChanged 相似。

我在更改ObservableCollection 中每个项目的数据时使用了我的问题中的this answer。但我不想再使用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 那样工作。

【问题讨论】:

  • 您在哪里收到您的消息?
  • 我有一个接收消息的函数。见编辑
  • 什么时候调用receiver方法?如果从不调用此方法,则您将永远不会订阅此事件。这个方法真的按预期调用了吗?
  • 当然如前所述。

标签: c# mvvm mvvm-light


【解决方案1】:

您已经提到您正在使用the answer from your previous question 以及这个“我不想再使用 INotifyPropertyChanged,因为我已经从这个问题继承了 ViewModelBase”

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

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

public class Fruit : ViewModelBase
{
    ....
}

【讨论】:

    猜你喜欢
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    • 2022-10-20
    • 2020-02-21
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多