Click here to Skip to main content
15,867,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

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">
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <EventSetter Event="PreviewMouseRightButtonDown" Handler="OnListBoxItemPreviewMouseRightButtonDown" />
                </Style>
            </ListBox.ItemContainerStyle>

            <ListBox.ContextMenu>
                <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" />
                </ContextMenu>
            </ListBox.ContextMenu>
        </ListBox>
</pre>


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.

Sincerly
Bert
Posted

1 solution

You can handle the event System.Windows.Controls.ContextMenu.ContextMenuOpening:
http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.contextmenuopening%28v=vs.110%29.aspx[^].

In the handler of this event, check up your condition and adjust the visibility of the menu items in question:
http://msdn.microsoft.com/en-us/library/system.windows.uielement.isvisible(v=vs.110).aspx[^].

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 (http://msdn.microsoft.com/en-us/library/system.windows.uielement.isenabled(v=vs.110).aspx[^]), and so on, depending on the status of the context: the application or the UI element owning the context menu.

—SA
 
Share this answer
 

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