Similar to How can I toggle the main menu visibility using the Alt key in WPF? I want to control menu visibility by pressing the ALT key.
I have the following in XAML:
<Menu Visibility="{Binding IsMenuVisable, Converter={StaticResource BooleanToVisibilityConverter}}">
<Menu.InputBindings>
<KeyBinding Key="LeftAlt" Command="{Binding ShowMenuCommand}"/>
<KeyBinding Key="RightAlt" Command="{Binding ShowMenuCommand}"/>
</Menu.InputBindings>
<MenuItem Header="_File">
<MenuItem Header="Open"/>
</MenuItem>
</Menu>
and the following in its View Model:
private ICommand _ShowMenu;
public ICommand ShowMenuCommand
{
get
{
if (_ShowMenu == null)
{
_ShowMenu = new RelayCommand(ShowMenu, CanShowMenu);
}
return _ShowMenu;
}
}
private void ShowMenu()
{
IsMenuVisable = !IsMenuVisable;
}
private bool CanShowMenu()
{
return true;
}
private bool _IsMenuVisable = false;
public bool IsMenuVisable
{
get { return _IsMenuVisable; }
set
{
if (_IsMenuVisable != value)
{
_IsMenuVisable = value;
OnPropertyChanged("IsMenuVisable");
}
}
}
No errors are reported in the output about it not being able to match up the bindings but when I press the alt key the command is not executed. I have also tried moving the InputBindings
into the window definition thinking that the menu needed focus for the InputBindings
events to fire and I still do not get them to fire.
Window XAML:
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<Window.DataContext>
<VM:MainWindowViewModel />
</Window.DataContext>
<Window.InputBindings>
<KeyBinding Key="LeftAlt" Command="{Binding ShowMenuCommand}"/>
<KeyBinding Key="RightAlt" Command="{Binding ShowMenuCommand}"/>
</Window.InputBindings>
Any thoughts and suggestions would be welcomed.