MVVM 最佳实践:视图模型之间的通信

2024-04-03

我的简化程序结构如下所示:

public class Manager
{
    public Item MyItem { get; set; }

    public void Recalculate(){ ... } 
}

public class Item
{
    public string SomeProperty { get; set; }
}

public class ManagerViewModel
{
    public Manager Model { get; set; }

    public ItemViewModel MyItem { get; set; }
}


public class ItemViewModel
{
    public Item Model { get; set; }

    public string SomeProperty
    {
        get => Model.SomeProperty;
        set 
        { 
            Model.SomeProperty = value;
            RaisePropertyChanged("SomeProperty");
        }
    }
}

When SomeProperty被改变在ItemViewModel, 我想Recalculate()在 Manager 内部触发。

Do I:

A)里面有一个PropertyChangedListenerManagerViewModel它监听其内部的属性更改MyItem,然后告诉它的模型Recalculate()

B) 允许 ItemViewModel 访问 Manager,因此它可以手动告诉 Manager 运行 Recalculate()

..

(B) 似乎有点反模式......每个 ViewModel 不应该只真正关心它自己的模型吗? (A) 有它自己的问题——我需要经常使用这种“重新计算”结构,而且似乎到处都有这些 PropertyChangedListener 有点混乱。我意识到有几种不同的方法可以解决这个问题,但我只是想知道在这种情况下“最佳实践”是什么。


As 埃德·普朗克特证实 https://stackoverflow.com/questions/46984421/mvvm-best-practices-communication-between-view-models#comment80916359_46984421,“选项 A”是最好的方法,因为它将 ViewModel 和 Model 的关注点分开。

ItemViewModel只关心它自己的模型,并且它只是通知正在监听的人它的属性已被更改。

ManagerViewModel聆听内部的变化ItemViewModel,然后执行Recalculate()在它自己的模型里面。

//Models

public class Manager
{
    public Item MyItem { get; set; }

    public void Recalculate(){ ... } 
}

public class Item
{
    public string SomeProperty { get; set; }
}

//ViewModels

public class ManagerViewModel
{
    public Manager Model { get; set; }

    public ItemViewModel MyItem { get; set; }

    public ManagerViewModel()
    {
        //Listen for property changes inside MyItem
        MyItem.PropertyChanged += ItemPropertyChanged;
    }

    //Whenever a Property gets updated inside MyItem, run Recalculate() inside the Manager Model 
    private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        Model.Recalculate();
    }
}


public class ItemViewModel
{
    public Item Model { get; set; }

    public string SomeProperty
    {
        get => Model.SomeProperty;
        set 
        { 
            Model.SomeProperty = value;
            RaisePropertyChanged("SomeProperty");
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MVVM 最佳实践:视图模型之间的通信 的相关文章

随机推荐