我希望WPF应用程序中的主菜单的行为类似于IE8中的主菜单:
我怎样才能做到这一点?它一定是代码吗?
添加了对提交的答案的响应,因为我仍然遇到问题:
我的Shell背后的代码现在看起来像这样:
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键,您需要检查SystemKey
的KeyEventArgs
属性,而不是通常用于大多数其他键的Key属性。
您可以使用此事件来设置bool
值,该值已在后面的Windows代码中声明为DependencyProperty
。
然后可以使用Visibility
将菜单的BooleanToVisibilityConverter
属性绑定(bind)到此属性。
<Menu
Visibility={Binding Path=IsMenuVisibile,
RelativeSource={RelativeSource AncestorType=Window},
Converter={StaticResource BooleanToVisibilityConverter}}
/>