开发者

WPF and MVVM: Enable a command only when a textbox has focus with implementation in ViewModel?

I have a command that I would like to be enabled only when a certain control has focus. I can do this with a routed command and command binding, but I'd like to keep the implementa开发者_如何学Gotion in my ViewModel.

Is a command binding and an event handler in the code behind the only way?


To handle this within the ViewModel, you will need to add the concept of the 'certain control' having focus into your view model, enabling the command when this focus state changes.You could do this by adding a boolean IsCertainControlFocussed property to your view model.

To update this state you have two options, either handle the GotFocus and LostFocus events in the code behind of you view and set this boolean property on your view model. Or use one of the MVVM framework absraction mechanisms. For example the MVVM Light framework has an EventToCommand behaviour which allows you to wire an event to a command exposed by your view model, which could set this property.

http://geekswithblogs.net/lbugnion/archive/2009/11/05/mvvm-light-toolkit-v3-alpha-2-eventtocommand-behavior.aspx

Which technique you use depends on how important it is to you to have no code-behind. Personally I do not follow this religiously, as long as the View Model has the right responsibilities, and is testable, a little it of code behind does no harm!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜