SLExtensions Commands的问题

来源:互联网 发布:演技最好的电影 知乎 编辑:程序博客网 时间:2024/06/05 20:51

项目中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. Commandis just a static event that can be raise from xaml. It allows a betterseparation between business logic and UI. When you add Input:CommandService.Command="MyButtonClick"in your xaml, it will attach a behavior to the xaml control raising theexecuted command when mouse down is pressed. When the it's raised itwill notify all its subscribers. So as you said you are attaching anevent handler for each button you are notified several times per click.The code to be invoked on command execution should be placed in a classmanaging your business logic. I often use "Controller" class in mysamples to handle this logic (you can see the showcasecontroller in thesource). This class is created one time and attaches an handler to theexecuted event. In your business logic, you can pass additional data byusing the Input:CommandService.CommandParameter on you xaml declaration.

 

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

 

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

 

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

SimpleCommand

RelayCommand

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

 

 

原创粉丝点击