Hello.
A window has a MenuItem binded to a collection, the MenuItem has ItemTemplate, which contains another MenuItem with an attached property using binding:
<Menu Background="Transparent">
<MenuItem ItemsSource="{Binding SomeThings}" Header="Menu">
<MenuItem.ItemTemplate>
<DataTemplate>
<MenuItem Header="{Binding MenuTitle}" WpfApplication30:MainWindow.KeyGesture="{Binding KeyGesture}"/>
</DataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>
</Menu>
The declaration of datasource and attached property:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DataContext = new {
SomeThings = new[]
{
new { MenuTitle = "Title 1", KeyGesture = new KeyGesture(Key.A, ModifierKeys.Control) },
new { MenuTitle = "Title 2", KeyGesture = new KeyGesture(Key.B, ModifierKeys.Control) },
new { MenuTitle = "Title 3", KeyGesture = new KeyGesture(Key.C, ModifierKeys.Control) },
} };
}
public static string GetKeyGesture(MenuItem obj)
{
return (string)obj.GetValue(KeyGestureProperty);
}
public static void SetKeyGesture(MenuItem obj, string value)
{
obj.SetValue(KeyGestureProperty, value);
}
public static readonly DependencyProperty KeyGestureProperty =
DependencyProperty.RegisterAttached("KeyGesture", typeof(KeyGesture), typeof(MainWindow),
new PropertyMetadata(OnSetKeyGestureCallback));
private static void OnSetKeyGestureCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var window = GetWindow(dependencyObject);
var keyGesture = (KeyGesture)e.NewValue;
window.KeyDown += (sender, keyArgs) =>
{
if (keyArgs.Key == keyGesture.Key && keyArgs.KeyboardDevice.Modifiers == keyGesture.Modifiers)
{
window.Background = Brushes.AntiqueWhite;
}
};
}
After OnSetKeyGestureCallback is called, a user can use a shortcut to perform an action. But OnSetKeyGestureCallback is called only after the menu is opened. So until the user opens the menu, shortcuts are not available. How to make OnSetKeyGestureCallback be called right after the window or the menu is loaded?