2016-01-21 63 views

回答

1

您可以将MainViewModel作为参考传递给其他视图模型。这样,您可以从其他视图模型访问MainViewModel中的数据。

public class MainViewModel 
{ 
    public AnotherViewModel avm { get; set; } 
    public int ImportantInfo { get; set; } 
    public MainViewModel() 
    { 
     avm = new AnotherViewModel(this); 
    } 
} 

public class AnotherViewModel 
{ 
    public MainViewModel mvm { get; set; } 
    public AnotherViewModel(MainViewModel mvm) 
    { 
     this.mvm = mvm; 
     MoreImportantINfo = this.mvm.ImportantInfo; 
    } 
    public int MoreImportantINfo { get; set; }  
} 

这种类型的引用只是一个可以用在较小项目中的例子。对于较大的项目,这个想法是通过依赖注入(DI)实现的。看看这篇文章的详细信息DI here

另一种方法是使用事件。请任何想要MainViewModel的数据的Viewmodel订阅MainViewModel用期望的数据调用的事件。

+0

设计使用依赖注入,还是通过事件聚合器进行消息传递或更好地在服务中共享内容都不是更好。 – TYY

+0

是的,除非它是一个较小的项目,否则最好使用DI。我只是给出一个如何共享资源的基本示例。 – mrsargent

+0

我将编辑我的帖子以指出。 – mrsargent