ViewModel 事件通信
我正在创建一个 WP7 应用程序,如果用户尚未登录,我希望显示一个登录屏幕。我有 Main.xaml
,它有一个视图模型 MainViewModel.cs
。对于登录或注册部分,我将它们作为 Grid
嵌入到 Main.xaml
中,但我认为将它们作为用户控件也可以正常工作。登录和注册部分将有自己的视图模型,可能是相同的,AccountViewModel.cs
,Grid
或用户控件有它的 DataContext< /代码> 设置为。
用户注册或登录后(发生在 AccountViewModel.cs
中),MainViewModel.cs
或 Main.xaml
的最佳方式是什么知道它已经完成,并且可以开始加载数据,或者做任何需要做的事情?
我最初的想法是使用 MVVM Light 的消息系统。注册/登录发生后,广播一条消息表明已完成,MainViewModel.cs
将注册到该消息并可以对其进行操作。
是否有其他方法或更正确的方法让 Main
知道它的孩子发生了什么事?
如果这太难理解,我可以添加代码示例。
I have a WP7 app I'm creating and I want a login screen to appear if the user hasn't logged in yet. I have Main.xaml
which has a view model MainViewModel.cs
. For the login or signup portions I have them embedded as a Grid
in Main.xaml
, but I would think having them as a user control would work fine also. The login and signup portions will have their own view model, possibly the same one for both, AccountViewModel.cs
, that the Grid
or user control has it's DataContext
set to.
After the user signs up or logs in, which occurs in AccountViewModel.cs
, what is the best way for MainViewModel.cs
or Main.xaml
to know that it is complete, and it can begin loading data, or doing whatever it needs to do?
My initial thought is to use MVVM Light's messaging system. After signup/login occurs, broadcast a message that it's complete, and MainViewModel.cs
will be registered to the message and can act on it.
Is there another way or more proper way of letting Main
know something has occurred in it's child?
If this is too hard to follow I can add code examples.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
消息系统(例如 MVVM Light 中的消息系统)是解耦此类操作并以您所描述的方式提供通知的好方法。不能说,因为我真的提倡其他任何事情。 Prism 库提供了一个
EventAggregator
,它执行相同的操作,但如果您已经在使用 MVVM Light,那么就继续使用它。A messaging system, such as the one in MVVM Light is a great way to decouple these kind of actions and provide notifications in the way you describe. Can't say as I'd advocate anything else really. The Prism library provides an
EventAggregator
, which does the same thing, but if you're already using MVVM Light, then stick with that.另一种方法是将此类信息 (IsLoggedIn) 存储在“全局视图模型”中,例如 SettingsViewModel.Instance。对于像设置这样具有全局意义的视图模型,恕我直言,这是一种很有意义的方法。如果您让此属性引发 PropertyChanged 事件,则可以在属性更改时动态修改 UI,例如平滑地隐藏登录 UI。
干杯,
洛朗
Another approach would be to store this kind of info (IsLoggedIn) in a "global view model" such as SettingsViewModel.Instance for example. For a viewmodel of global meaning like Settings, it is an approach that makes a lot of sense IMHO. If you make this property raise the PropertyChanged event, this allows you to dynamically modify the UI when the property changes, and hide the login UI smoothly for instance.
cheers,
Laurent