开发者

How a command from main window be handled in a usercontrol view model

In my application I have several user controls in a window. These user controls need to communicate to each other. My approach is as below

  1. user control A fire a command which is to be handled by user control B.
  2. main window recieves the command and fire a command to B
  3. user control B handles the command.

My problem is how the main window can fire a command which can be handl开发者_开发问答ed in the VIEW MODEL of user control B?

Update:

SOLVED: One gloabl static RelayCommand for communication from the MainWindow to B and one Global RoutedCommand for communication from A to Main Window. Thank you for the responses.


The question is not tagged mvvm (yet), but I am assuming it since you mention a ViewModel. So to begin with, let's agree that ViewModels handle commands, not controls. If a control want to respond to a command being executed, expose a suitable CommandExecuted event that the control (View) can attach a handler to.

There is however another unknown that I cannot blindly assume:

Do you take it for granted that user controls A and B exist at the same time? If yes, then a very simple and low-tech solution would be to maintain references to both ViewModels at some level (perhaps the ViewModel for the Window itself?) and "bubble" the command up to there, where the dispatch to ViewModel B will occur. If not (in which case control B might not exist), what is the desired behavior?

With the information you have given so far, I 'd suggest using the Event Aggregator/Mediator pattern implementation of your MVVM framework. For example, Prism has EventAggregator; MVVM Light has Messenger; etc.


I would think that you'd want to have a dependency property on B that the main window could bind to. Your DP on B would then take the request and call it's view model.

The main window should not know anything about the inner workings of a Control. It should only know about the exposed properties from the control.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜