如何在MVVM中使用相同的ViewModel拥有多个视图? [英] How to have multiple Views using the same ViewModel in MVVM?

查看:222
本文介绍了如何在MVVM中使用相同的ViewModel拥有多个视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WPF和MVVM的新手,在尝试在两个单独的视图中将DataContext设置为同一ViewModel实例时遇到一个问题.

I am new to both WPF and MVVM and a came across an issue when attempting to set the DataContext to the same instance of my ViewModel in two separate views.

这是因为:

<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>

将为每个视图创建视图模型的新实例.

would create a new instance of the view model for each view.

为了解决这个问题,我决定创建一个类,该类存储我使用的每个ViewModel的静态实例.然后,在每个视图的cs文件中,然后将DataContext设置为此静态类中的相应ViewModel.

To get around this I decided to create a class that stored static instances of each ViewModel I used. Then in the cs file of each view I would then set the DataContext to the appropriate ViewModel from this static class.

这是可行的,但对于大型程序而言似乎并不是最好的主意,在大型程序中可能同时需要ViewModel的多个实例.

This works but doesn't seem the best idea for larger programs where the multiple instances of the ViewModel may be needed simultaneously.

解决此问题的更好方法是什么-是否存在使用ViewModel的相同实例的多个View的合理方法?

What are better approaches to this problem - Are there sound ways to have multiple Views using the same instance of a ViewModel?

还是这种方法是不好的做法-我应该为每个ViewModel设计一个带有一个View的程序吗?

Or is this approach bad practice - Should I be designing a program with one View for every ViewModel?

谢谢!

推荐答案

您可以在App.xaml中实例化该视图模型,以便整个应用程序都可以访问它.

You can instantiate that view model in App.xaml so that it is accessible to the whole application.

<Application.Resources>
    <local:ViewModel x:Key="sharedViewModel" />
</Application.Resources>

然后,在您想要使用该数据上下文的视图中,执行以下操作...

Then in your views when you want to use that datacontext, you do the following...

DataContext="{StaticResource sharedViewModel}"

这篇关于如何在MVVM中使用相同的ViewModel拥有多个视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆