简体   繁体   中英

My WPF ContextMenu is not dismissing when I click elsewhere

I have a WPF ContextMenu instance declared in my XAML like this

<Window.ContextMenu>
    <ContextMenu>
        <MenuItem Header="Do Nothing"/>
        <Separator/>
        <MenuItem Header="{x:Static p:Resources.MenuExit}" Click="IconMenu_Exit"/> 
    </ContextMenu>
</Window.ContextMenu>

I'm using the WinForms NotifyIcon to display a tray icon like this

_notifyIcon = new System.Windows.Forms.NotifyIcon();
_notifyIcon.Icon = Properties.Resources.mainicon;
_notifyIcon.Visible = true;
_notifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(OnTrayIconMouseClick);

The implementation of the mouse click handler is this

private void OnTrayIconMouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        ContextMenu.IsOpen = true;
    }
}

This displays the context menu and clicking on the menu items dismisses it, but if I just click away on another window, the context menu stays visible. This seems like strange default behavior. Is there another way to display the context menu other than IsOpen or do I have to explicitly hide the context menu somehow?

Edit: I don't know if it matters but the window's DataContext is set to this in its code-behind.

Edit2: The context menu dismisses properly if it's invoked by right clicking on the actual main window but not from the tray icon.

检查您是否未将StaysOpen属性定义为true。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM