3

I have a ViewModel of the form:

class VM : DependencyObject
{
    // This class exposes a command to data binding to delete things from the model
    public static DependencyProperty DeleteProperty = DependencyProperty.Register(/*...*/);

    public static ICommand Delete {
        get {
            return (ICommand)this.GetValue(DeleteProperty);
        }
        set {
            this.SetValue(DeleteProperty, value);
        }
    }
}

For a ListBoxItem I would like to data bind execution of ApplicationCommands.Delete to this ICommand exposed by this ViewModel. That way, when someone presses the menu item that raises ApplicationCommands.Delete, this particular delete will be chosen if focus is currently on this thing:

<!-- Elsewhere... -->
<MenuItem Text="Delete" Command="ApplicationCommands.Delete" />

<!-- Some data template with DataContext == the above DependencyObject -->
<Grid>
    <Grid.CommandBindings>
        <!--
        I want ApplicationCommands.Delete to forward to the command {Binding Delete}
        -->
        <CommandBinding Command="ApplicationCommands.Delete" 
                        ???
                        />
    </Grid.CommandBindings>
</Grid>

... but CommandBinding can only bind to event handlers; not other commands, so I can't use MVVM-style data binding to attach it. Is there some MVVM mechanism I can use here or am I forced into adding code-behind for the CommandBinding?

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552

1 Answers1

4

You can use this tutorial to bind ApplicationCommands.
1.Add command binding collection property in your view model:

public CommandBindingCollection CommandBindings { get; }

public YourViewModel()
{
//Create a command binding for the delete command
var deleteBinding = new CommandBinding(ApplicationCommands.Delete, DeleteExecuted, DeleteCanExecute);

//Register the binding to the class
CommandManager.RegisterClassCommandBinding(typeof(YourViewModel), DeleteBinding);

//Adds the binding to the CommandBindingCollection
CommandBindings.Add(deleteBinding);
}
  1. Create attached property as mentioned in the tutorial.

  2. Then bind attached property in your UI.

Nikita Shrivastava
  • 2,978
  • 10
  • 20
  • Ah, so you mean data bind to a CommandBindingCollection instead of a command? Clever. I don't like that this makes me specify which routed command in the ViewModel (rather than XAML) but its better than what I've got now :) – Billy ONeal Aug 27 '15 at 15:06