tolsen64
tolsen64

Reputation: 999

WPF ListBox in MenuItem. How to keep menu from closing when clicking in ListBox?

I'm attempting to create Excel-like sorting/filtering in a DataGrid. I created this ContextMenu with a ListBox inside the Header of a MenuItem.

The ContextMenu

When I click on a checkbox or the text of the checkbox, it behaves as expected. However, if I click in the whitespace of the checkbox/listbox or in the header space outside of the listbox, the ContextMenu closes.

It's not in the screenshot yet, but i'll be adding OK & Cancel buttons below the listbox. Clicking one of them is when I want the ContextMenu to close.

In case you need the XAML, here it is:

    <MenuItem x:Name="miListBox"
              Focusable="False">
        <MenuItem.Header>
                <ListBox MaxHeight="150" Focusable="False">

                </ListBox>
        </MenuItem.Header>
    </MenuItem>

Upvotes: 0

Views: 984

Answers (1)

King King
King King

Reputation: 63317

The ContextMenu has a property called StaysOpen. Just set it to true to not allow it to auto-close and then you need to use the IsOpen property to open/close it manually:

<ContextMenu StaysOpen="true">
    <ContextMenu.Resources>

    <!-- ... --->
</ContextMenu>

Edit:

From MSDN, the StaysOpen property should have worked as the name suggests however looks like it's simply useless. Because it does not work expectedly. Somehow the IsOpen is always set to false automatically when one of the MenuItems is clicked or when we click outside the ContextMenu. And as in the documentation about StaysOpen, the ContextMenu is still closed when IsOpen is set to false. The problem here is we don't set that manually but it's automatically set somehow and hence the uselessness of StaysOpen.

We can set the StaysOpenOnClick on each MenuItem instead:

<ContextMenu>
    <ContextMenu.Resources>
         <Style TargetType="MenuItem">
              <Setter Property="StaysOpenOnClick" Value="True"/>
         </Style>
    </ContextMenu.Resources>
    <!-- ... -->
</ContextMenu>

Upvotes: 2

Related Questions