Eric after dark
Eric after dark

Reputation: 1808

Unable To Close Custom ContextMenu Window

Everything in my WPF program is generally custom. In this problem I have a custom menu button that acts kind of like the MS Office button from 2007. When clicked it brings down a context menu. My problem is trying to get it to close. After being opened, the Context Menu never closes. I would like if it would close when the user clicks anywhere outside of the menu box, like how a normal Context Menu would act.

This is what I have so far:

.xaml Window:

<!--- MAIN MENU BUTTON -->
        <Button Click="Button_Click_1" Margin="5,4,0,0" Name="Button_1" Height="50" VerticalAlignment="Top" HorizontalAlignment="Left" Width="49.758">
            <!--- MAIN MENU -->
            <Button.ContextMenu>
                <ContextMenu x:Name="MainContextMenu" PlacementRectangle="{Binding RelativeSource={RelativeSource Self}}" MouseLeave="ContextMenuMouseLeave" >
                    ...                
            </Button.ContextMenu>

Right now I am just trying to get it to close when the mouse leaves the menu, because I do not know what keyword to use when I am describing a click outside of the Context menu. As you can see, when the mouse leaves the menu, the program calls the "ContextMenuMouseLeave" function.

.xaml.cs code-behind:

//CLOSE CONTEXT MENU
        private void ContextMenuMouseLeave(object sender, EventArgs e)
        {
            MainContextMenu.IsOpen = false;
        }

Apparently in WPF the Context Menu object does not contain Close(), or Hide(). I have also tried MyContextMenu.IsOpen = false; and SendKeys.SendWait("{ESC}"); with no luck. How do I get this menu window to close again in WPF??

-I've posted this question on another forum as well and I was wondering if maybe a Context Menu isn't the best way to go? Apparently Context Menus are mainly displayed when a used right clicks something. I'm going to be using this button to open my program's main menu. Should I be using some other object?

Thank you.

Upvotes: 1

Views: 1602

Answers (1)

TrueEddie
TrueEddie

Reputation: 2233

You could set MainContextMenu.Visibility to Visibility.Collapsed

Upvotes: 2

Related Questions