在 MVVMLight 中设置 ViewModel 的 DataContext
我有一个关于 MVVM 模式的问题。所以我不确定我是否完全理解了它。
我的场景:
- ViewModelLocator :将请求的 ViewModel 提供给指定的视图。
- LoginViewModel:LoginView 的 ViewModel
- MainPageViewModel:MainPageView 的 ViewModel
我的示例应用程序。很简单:用户可以登录并进入 MainPageView。
MainPageView 使用 MainPageViewModel。我使用 MVVMLight 框架的信使从 LoginView 导航到 MainPageView。
Messenger.Default.Register<LoginPerson>(this, Constants.NavigateLogin,
person => this.Window.SetContentControl(new MainPage(person)));
我将登录者传递给视图。 MainPage - View 会将登录者设置为其 ViewModel (=> MainPageViewModel)。
这种方式正确吗?我不这么认为:-) 如何在 ViewModel 之间进行通信?感谢您的建议。
问候,亲
I've got a question of the MVVM-Pattern. So I'm not sure, that I've had understand it completely.
My scenario:
- ViewModelLocator : Provide the requested ViewModel to a specified view.
- LoginViewModel: ViewModel for the LoginView
- MainPageViewModel: ViewModel for the MainPageView
My example app. is simple: The user can login and comes to the MainPageView.
The MainPageView uses the MainPageViewModel. I use the messenger of the MVVMLight framework to navigate from the LoginView to the MainPageView.
Messenger.Default.Register<LoginPerson>(this, Constants.NavigateLogin,
person => this.Window.SetContentControl(new MainPage(person)));
I pass the loggedin person to the View. The MainPage - View will set the the logged in person to its ViewModel (=> MainPageViewModel).
Is this way correct? I don't think so :-) How can I communicate between the ViewModels? Thanks for your advices.
Regards, pro
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 MVVM 时,您的应用程序是 ViewModel,而不是 View。您不应该处理任何类型的业务逻辑,例如导航或从视图传递用户对象。 View 只是一个漂亮的层,允许用户轻松地与 ViewModel 进行交互。
通常在这种情况下,我使用
ShellViewModel
,其中包含一个CurrentPage
属性,该属性设置为当前页面的任何 ViewModel。我还将在ShellViewModel
中存储CurrentUser
属性。您的 ShellViewModel 是您的启动对象,启动时
CurrentPage
将是LoginViewModel
。当用户成功登录时,LoginViewModel
广播一条LoginSuccessful
消息,参数为CurrentUser
和ShellViewModel
> 将拾取该消息并根据消息参数设置CurrentUser
,并将CurrentView
切换到新的MainPageViewModel
例如,请查看我的帖子这里
When using MVVM, your application is your ViewModels, not your Views. You should not be handling any kind of business logic such as navigation or passing User objects around from your Views. The View is simply a pretty layer that allows the user's to interact with your ViewModels easily.
Usually in this kind of situation I use a
ShellViewModel
which contains aCurrentPage
property that is set to whatever ViewModel is the CurrentPage. I would store aCurrentUser
property in theShellViewModel
as well.Your ShellViewModel is your startup object, and on startup the
CurrentPage
would be aLoginViewModel
. When the user successfully logs in, theLoginViewModel
broadcasts aLoginSuccessful
message with a parameter of theCurrentUser
, and theShellViewModel
would pickup that message and set theCurrentUser
based on the message parameters, and would switchCurrentView
to a newMainPageViewModel
For an example, check out my post here