Search code examples
c#wpfmvvmcommandicommand

How to use RoutedUICommand?


I'm currently refactoring my program to use MVVM. I have tried to use commands for 2 days now, but I simply cannot find a good way to use them.
Shortcuts can only be used with RoutedCommands and RoutedUICommands, on which the CanExecute and Executed eventhandler must be defined in the codebehind file to access ui-elements, which reduces reusability.
If the commands are defined in the viewmodel, ui-elements cannot be accessed.
2 examples to illustrate what I'm saying here:

  1. I have a list of items in a DataGrid. The selected item should be opened in another window when a doubleclick on the DataGrid is performed. How do I call the Command on the MouseDoubleClick event?
  2. A ComboBox holds a List of values. A Button opens a new Window that adds something to this list. After the Window is closed, the new value should be selected.
    I think the CommandTarget Property should be used, but how is this possible with RoutedUICommands?

Solution

  • Since the desired answer cannot be given by question I will answer it myself.
    I was using the Commands as static properties of my viewmodel, which was a bad approach. After switching to normal Properties, everything works like a charm!