简体   繁体   English

使WPF窗口的行为类似于上下文菜单(正确显示/隐藏它)

[英]Make a WPF Window behave like a Context Menu (show/hide it properly)

I want to make a WPF Window that behaves like a context menu. 我想制作一个行为类似于上下文菜单的WPF窗口。

So, for instance - when I show the wpf window, I want it to be the topmost window and from there on out, if the user clicks anything outside of that window I want the window to be hidden again. 因此,例如,当我显示wpf窗口时,我希望它成为最顶层的窗口,然后从那里开始,如果用户单击该窗口之外的任何内容,我都希望该窗口再次隐藏。

So far I have tried quite a few techniques but the only one that I found that kinda works is shown here. 到目前为止,我已经尝试了很多技术,但是这里显示了我发现还可以的唯一技术。 It works the very first time but never again after that: 它是第一次工作,但此后不再工作:

public TheWindow()
{
    InitializeComponent();
    this.Topmost = true;
}

void ShowMe()
{
    this.Show();
    this.CaptureMouse();
}

void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
    /// TODO: Check if they clicked outside the window here!
    this.ReleaseMouseCapture();
    this.Hide();
}

I also tried just handling the Deactivated event, but it also only works the first time for some reason. 我也尝试仅处理Deactivated事件,但由于某种原因,它也只能在第一次使用。

Is PopUp not sufficient for your needs? PopUp是否不足以满足您的需求? It has a StaysOpen property that lets it act like you describe. 它具有一个StaysOpen属性,可使其表现得像您描述的那样。

Don't know how helpful this will be, but if you don't necessarily need a Window, one technique I have used is placing a UserControl inside a Window. 不知道这会有多大帮助,但是如果您不一定需要Window,我使用的一种技术是将UserControl放在Window内。

Depending on whatever condition, you would show a context menu. 根据任何条件,您将显示一个上下文菜单。 Inside the menu I placed a menu item and inside that just place the user control. 在菜单内部,我放置了一个菜单项,而在其中仅放置了用户控件。 It will behave exactly like what you want. 它的行为将完全像您想要的。 You can show the context menu anywhere on the screen and clicking outside its bounds will close it. 您可以在屏幕上的任意位置显示上下文菜单,然后单击其边界将其关闭。

See: http://andyonwpf.blogspot.com/2006/10/dropdownbuttons-in-wpf.html for an example of how one would show a context menu anywhere on the screen. 有关如何在屏幕上的任意位置显示上下文菜单的示例,请参见: http : //andyonwpf.blogspot.com/2006/10/dropdownbuttons-in-wpf.html Also, you would need to override the default template for MenuItem so that mousing over the menu item doesn't highlight it. 另外,您将需要覆盖MenuItem的默认模板,以便将鼠标悬停在菜单项上不会使其突出显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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