Reputation: 1705
Is there a simple property that enables the menu class to autohide after a set number of seconds? I've searched MSDN but am unable to find a suitable property.
Upvotes: 0
Views: 2237
Reputation: 30840
By default Menus don't support this, but by little modifications, you can easily implement this behavior.
For example:
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();
}
}
Can be used like:
<local:AutoHideMenuItem Header="File" AutoHideDelay="3">
<MenuItem Header="New"></MenuItem>
<MenuItem Header="Open"></MenuItem>
<MenuItem Header="Close"></MenuItem>
<MenuItem Header="Exit"></MenuItem>
</local:AutoHideMenuItem>
Which will close this menu after 3 seconds. Of course its rough code and you will need to make changes to it to suit your scenario.
Upvotes: 2