如何使用WPF中的Alt键切换主菜单的可见性? [英] How can I toggle the main menu visibility using the Alt key in WPF?
问题描述
我希望WPF应用程序中的主菜单的行为类似于IE8中的主菜单:
I'd like the main menu in my WPF app to behave like the main menu in IE8:
- 应用启动时不可见
- 按下并释放Alt使其可见
- 再次按下并释放Alt使其再次不可见
- 重复直到无聊
我该怎么做?一定是代码吗?
How can I do this? Does it have to be code?
添加了对我提交的答案的答复,因为我仍然遇到问题:
我的Shell背后的代码现在看起来像这样:
My Shell code-behind now looks like this:
public partial class Shell : Window
{
public static readonly DependencyProperty IsMainMenuVisibleProperty;
static Shell()
{
FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata();
metadata.DefaultValue = false;
IsMainMenuVisibleProperty = DependencyProperty.Register(
"IsMainMenuVisible", typeof(bool), typeof(Shell), metadata);
}
public Shell()
{
InitializeComponent();
this.PreviewKeyUp += new KeyEventHandler(Shell_PreviewKeyUp);
}
void Shell_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (e.SystemKey == Key.LeftAlt || e.SystemKey == Key.RightAlt)
{
if (IsMainMenuVisible == true)
IsMainMenuVisible = false;
else
IsMainMenuVisible = true;
}
}
public bool IsMainMenuVisible
{
get { return (bool)GetValue(IsMainMenuVisibleProperty); }
set { SetValue(IsMainMenuVisibleProperty, value); }
}
}
推荐答案
您可以在窗口上使用PreviewKeyDown
事件.要检测 Alt 键,您需要检查KeyEventArgs
的SystemKey
属性,而不是通常用于大多数其他键的Key属性.
You can use the PreviewKeyDown
event on the window. To detect the Alt key you will need to check the SystemKey
property of the KeyEventArgs
, as opposed to the Key property which you normally use for most other keys.
您可以使用此事件来设置bool
值,该值已在后面的Windows代码中声明为DependencyProperty
.
You can use this event to set a bool
value which has been declared as a DependencyProperty
in the windows code behind.
然后可以使用BooleanToVisibilityConverter
将菜单的Visibility
属性绑定到此属性.
The menu's Visibility
property can then be bound to this property using the BooleanToVisibilityConverter
.
<Menu
Visibility={Binding Path=IsMenuVisibile,
RelativeSource={RelativeSource AncestorType=Window},
Converter={StaticResource BooleanToVisibilityConverter}}
/>
这篇关于如何使用WPF中的Alt键切换主菜单的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!