Looking at MenuItem
in reflector, we can see how the MenuItem picks up the Header
/InputGesture
values, which is:
private static object CoerceInputGestureText(DependencyObject d, object value)
{
RoutedCommand command;
MenuItem item = (MenuItem) d;
if ((string.IsNullOrEmpty((string) value) &&
!item.HasNonDefaultValue(InputGestureTextProperty)) &&
((command = item.Command as RoutedCommand) != null))
{
InputGestureCollection inputGestures = command.InputGestures;
// Get appropriate gesture....
}
return value;
}
There is similar code to coerce the Header property based on the current command, but in this case it looks for a RoutedUICommand
. This tells us, the commands must be an instance of RoutedCommand
/RoutedUICommand
in order to leverage this feature of MenuItem
.
Looking at RoutedCommand
in reflector, there is not an easy way to create a DelegateCommand
that derives from RoutedCommand
, because it's CanExecute
/Execute
methods are not virtual.
We could code something like:
public class DelegateCommand : RoutedCommand, ICommand
{
bool ICommand.CanExecute(object parameter) {
// Insert delegate can execute logic
}
void ICommand.Execute(object parameter) {
// Insert delegate execute logic
}
}
But this does not prevent the non-explicit CanExecute
/Execute
methods on RoutedCommand
from being called. Which may or may not be an issue.
Alternatively, we can create a custom MenuItem
that is smart enough to look for our DelegateCommand (or somewhere else) and use it's text/gestures.
public class MyMenuItem : MenuItem {
static MyMenuItem() {
InputGestureTextProperty.OverrideMetadata(typeof(MyMenuItem),
new FrameworkPropertyMetadata(string.Empty, null, CoerceInputGestureText));
}
private static object CoerceInputGestureText(DependencyObject d, object value) {
MenuItem item = (MenuItem)d;
var command = item as DelegateCommand;
if ((string.IsNullOrEmpty((string)value) &&
DependencyPropertyHelper.GetValueSource(item, InputGestureTextProperty).BaseValueSource == BaseValueSource.Default &&
command != null) {
InputGestureCollection inputGestures = command.InputGestures;
// Get appropriate gesture....
}
// Call MenuItem Coerce
var coerce = InputGestureTextProperty.GetMetadata(typeof(MenuItem)).CoerceValueCallback;
return coerce(d, value);
}
}