是否有一个简单的属性可以让菜单类在设定的秒数后自动隐藏?我搜索了MSDN,但无法找到合适的房产。
答案 0 :(得分:2)
默认情况下,菜单不支持此功能,但只需稍加修改,您就可以轻松实现此行为。
例如:
public class AutoHideMenuItem : MenuItem
{
DispatcherTimer timer;
private Int32 _autoHideDelay;
public Int32 AutoHideDelay
{
get
{
return _autoHideDelay;
}
set
{
_autoHideDelay = value;
timer.Interval = TimeSpan.FromSeconds(AutoHideDelay);
}
}
public AutoHideMenuItem()
{
MouseMove += new MouseEventHandler(AutoHideMenuItem_MouseMove);
ContextMenuOpening += new ContextMenuEventHandler(AutoHideMenuItem_ContextMenuOpening);
SubmenuClosed += new RoutedEventHandler(AutoHideMenuItem_SubmenuClosed);
timer = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher);
timer.Interval = TimeSpan.FromSeconds(AutoHideDelay);
timer.Stop();
timer.Tick += new EventHandler(timer_Tick);
}
void timer_Tick(object sender, EventArgs e)
{
if (IsSubmenuOpen && !IsMouseOver)
{
IsSubmenuOpen = false;
}
}
void AutoHideMenuItem_MouseMove(object sender, MouseEventArgs e)
{
timer.Stop();
timer.Start();
}
void AutoHideMenuItem_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
timer.Start();
}
void AutoHideMenuItem_SubmenuClosed(object sender, RoutedEventArgs e)
{
timer.Stop();
}
}
可以像:
一样使用 <local:AutoHideMenuItem Header="File" AutoHideDelay="3">
<MenuItem Header="New"></MenuItem>
<MenuItem Header="Open"></MenuItem>
<MenuItem Header="Close"></MenuItem>
<MenuItem Header="Exit"></MenuItem>
</local:AutoHideMenuItem>
3秒后将关闭此菜单。当然,它的粗略代码,您需要对其进行更改以适应您的情况。