使用 MVVM 处理应用程序事件的首选方法
使用 MVVM(在我的例子中为 MVVM Light)时处理应用程序中所有事件的首选方法是什么?因此,诸如 Application_Launching
、Application_Activated
、Application_Deactivated
和 Application_Closing
等。
我的想法是在视图模型可以订阅的每个事件上广播一条消息。我的另一个想法是直接从 App.xaml.cs 事件调用视图模型上的方法。
What is the preferred method of handling all the events from the App when using MVVM (MVVM Light in my case)? So, things like Application_Launching
, Application_Activated
, Application_Deactivated
, and Application_Closing
.
My thought is to broadcast a message on each event that the view models can subscribe to. My other thought would be to call a method on the view models directly from the App.xaml.cs
events.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
上面提到的那些事件与视图完全无关,因为视图要么会被这些事件创建,要么会被销毁。
这一点使得事件传播到 ViewModel 代码不需要采用 MVVM 方式,主要是因为这些事件引发时间中不涉及 View。
为了正确实现“关注点分离”,您可以让 MainViewModel(主要是单例)拥有所有 4 个方法并直接从 App.xaml 调用它。否则事件委托(信使)会更干净。
我假设您想对这些事件执行一些常规操作,例如isolatedStorage 或序列化/反序列化操作。
Those events you have mentioned above have nothing to do with the View at all, because the View is either going to get created or going to be destroyed with those events.
That point makes the events propogate in to ViewModel code need not be a MVVM way mainly because there is no View involved in those event raising times.
Just to implement this properly for a 'Seperation of Concern', you can have you MainViewModel (Mostly singleton) has all 4 methods and call it directly from App.xaml. Or else an event delegate ( messenger) would be more clean.
I assume you want to do some general operations on those events like IsolatedStorage or serialization/deserialization operations.
我将所有文件保存在单独的 DLL 中(模型在 App.Model.dll 中,视图在 App.Views.dll 中,等等),因此主启动运行时中的代码非常少。我使用中央控制器并挂钩应用程序级别的事件、中央设置等特定于应用程序的事件。
I keep all my files in seperate DLLs ( Models in App.Model.dll, Views in App.Views.dll, etc...) so there's very little code in the main boot runtime. I use a central controller and hook app level events, central settings etc to it that are app specific.