Question

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?
Was it helpful?

Solution 2

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!

OTHER TIPS

It sounds to me like you need to use the RelayCommand, or similar. This is a class that extends the ICommand interface and not the RoutedCommand... you can think of it as a delegate command. Instead of defining a separate class for each command, you can simply define the command logic and the canExecute handler inline. Here is a simplified example:

public ICommand SaveCommand
{
    get { return new RelayCommand(execute => Save(), canExecute => CanSave()); }
}

You can find an implementation of it in the RelayCommand.cs page on GitHub and a description of it in the Commands, RelayCommands and EventToCommand page on MDSN Magazine.

Finally, you can set up keyboard shortcuts for these commands using the KeyBinding class:

<KeyBinding Gesture="CTRL+S" Command="{Binding Save, Mode=OneWay}" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top