tags:

views:

1618

answers:

2

I want to make a WPF Window that behaves like a context menu.

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.

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.

+3  A: 

Is PopUp not sufficient for your needs? It has a StaysOpen property that lets it act like you describe.

Robert Macnee
+1  A: 

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.

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. Also, you would need to override the default template for MenuItem so that mousing over the menu item doesn't highlight it.

siz