Reputation: 703
I guess I'll start by saying that my WPF program has a ListBox. Obviously within this are some ListBoxItems. Each ListBoxItem is populated with data, with some ListBoxItems being wider or narrower than others.
To give a ListBoxItem a context menu, I put a border around the data template for the ListBoxItem and attach the context menu to that border. It works well enough, but there's a snag. Let me show you an image to illustrate:
So you can see here the top item has two items within it. Those said items have black borders and in this image the first of those is selected. As you can see, however, that blue selection area is greater than the item itself (denoted by the black border). Now that outside area can select a ListBoxItem, but if I right click in that extra area of course it doesn't give me the context menu for that item.
I think my way is a little wrong because this makes things rather confusing for the user. I just wonder what better method there might be and I was hoping someone here might help me with it.
Thanks.
Upvotes: 0
Views: 32
Reputation: 12276
You can attach a contextmenu to the listboxitem itself. Roughly:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
.....
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
Or you could put the contextmenu on the listbox itself:
<ListBox>
<ListBox.ContextMenu>
<ContextMenu>
...
</ContextMenu>
</ListBox.ContextMenu>
You might think... ah but how do I know which item they clicked. This will be selected. You can bind selecteditem and work with that. You didn't ask about how to bind or suchlike but you might find defining the contextmenu in the resources of the listbox or window is simplest. That way it's in the datacontext of the window and you can bind to commands in it's viewmodel.
Upvotes: 1