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 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 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 execution should 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 and attaches an handler to the executed event. In your business 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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值