0
我正在使用设计模式MVVM创建一个WPF应用程序,在下一步中,我需要在另一个窗口中使用MainWindow中显示的DataGrid的内容。 有没有办法使用ViewModels传递的其他Windows中的特定窗口中创建的项目?在WPF MVVM的其他视图中使用DataGrid的内容
我正在使用设计模式MVVM创建一个WPF应用程序,在下一步中,我需要在另一个窗口中使用MainWindow中显示的DataGrid的内容。 有没有办法使用ViewModels传递的其他Windows中的特定窗口中创建的项目?在WPF MVVM的其他视图中使用DataGrid的内容
您可以将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
用期望的数据调用的事件。
设计使用依赖注入,还是通过事件聚合器进行消息传递或更好地在服务中共享内容都不是更好。 – TYY
是的,除非它是一个较小的项目,否则最好使用DI。我只是给出一个如何共享资源的基本示例。 – mrsargent
我将编辑我的帖子以指出。 – mrsargent