Click here to Skip to main content
14,838,196 members
Please Sign up or sign in to vote.
0.00/5 (No votes)

I have a listbox with elements and a contextmenu on it.
But I want to display some MenuItems only if there are > 1 items selected in the ListBox.

My code is currently this:

<ListBox x:Name="lsbChampionsInGroup" Margin="10,220,5,11" SelectionMode="Multiple" HorizontalAlignment="Left" Width="160" RenderTransformOrigin="0.5,0.5">
                <Style TargetType="{x:Type ListBoxItem}">
                    <EventSetter Event="PreviewMouseRightButtonDown" Handler="OnListBoxItemPreviewMouseRightButtonDown" />

                <ContextMenu Name="cmChampionsInGroup">
                    <MenuItem Header="Unselect all" Click="UnselectAllChampions" />
                    <Separator Background="CornflowerBlue" />
                    <MenuItem Header="Remove" Click="btnRemoveChampionsFromCurrentGroup_Click"/>
                    <Separator Background="CornflowerBlue" />
                    <MenuItem Header="Copy" Click="CopySelectedChampionsInCurrentGroup" />
                    <MenuItem Header="Paste" Click="PasteSelectedChampions" />

The ItemContainerStyle makes sure I do not unselect an item if a user right-clicks on it.

I would have to do this for 3 ListBoxes.


1 solution

You can handle the event System.Windows.Controls.ContextMenu.ContextMenuOpening:[^].

In the handler of this event, check up your condition and adjust the visibility of the menu items in question:[^].

In other cases, this event handler is the point where you can modify the content of the context menu itself (its items): add/remove menu items, change their appearance, enable/disable status ([^]), and so on, depending on the status of the context: the application or the UI element owning the context menu.


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900