Reputation: 106530
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
?
Upvotes: 3
Views: 1865
Reputation: 3018
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);
}
Create attached property as mentioned in the tutorial.
Then bind attached property in your UI.
Upvotes: 4