`
ribishuangba
  • 浏览: 291041 次
文章分类
社区版块
存档分类
最新评论

SLExtensions Commands的问题

 
阅读更多

项目中Slilverlight使用MVVM模式时View的用户交互事件使用的SLExtensions 中的Commands来实现调用ViewModel的事件处理方法。很自然的想到在ViewModel的构造方法中来注册事件处理方法。然而SLExtensions中的Commands采用的是类似静态事件的机制,若程序中有多个同一类型的ViewModel的实例时,事件将被触发多次(等于view modle实例数)因为,每个viewmodel的实例化时都订阅了一遍事件。

看到SLExtension讨论组中有人提到类似问题 ,该项目成员titaye的回答是:

I think you missunderstood how the command pattern is working. Command is just a static event that can be raise from xaml. It allows a better separation betweenbusiness logicand UI. When you add Input:CommandService.Command="MyButtonClick" in your xaml, it will attach a behavior to the xaml control raising the executed command when mouse down is pressed. When the it's raised it will notify all its subscribers. So as you said you are attaching an event handler for each button you are notified several times per click. The code to be invoked on command executionshould be placed in a class managing your business logic. I often use "Controller" class in my samples to handle this logic (you can see the showcasecontroller in the source). This class is created one time andattaches an handler tothe executed event. In yourbusiness logic, you can pass additional data by using the Input:CommandService.CommandParameter on you xaml declaration.

看来这个Command处理方法他是在一个唯一实例的controller中使用的,这不太方便于是回复:

You have a singleton controller to prevent the static commands from broadcasting multiple times which is not expected in business logic, but I need viewmodel to handle the commands requested from views because viewmodels have the state of the views and operations to handle the requests. So viewmodel have to subscribe the commands (static events) and in some cases, I have multiple viewmodels of same type instantiated, then would run into the big problem of same command was handled multiple times (as many as viewmodels' instances) - I know this is not the way that commands should be used as they are static events, but indeed I need viewmodels to subscribe their views' commands not a controller to do this

准备将项目中的Commands机制换成Prism的DelegateCommand。其他Command机制包括:

SimpleCommand

RelayCommand

有人做了一个简单的总结:http://dotnet.org.za/rudi/archive/2009/03/05/the-power-of-icommand.aspx

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics