tags:

views:

420

answers:

1

Hi everyone,

I've got a scenario where I have a GroupBox which has a bit of content in it. I'm looking to add ContextMenu to that GroupBox and have that menu shown when the user right-clicks anywhere in the box.

The problem I have is that the context menu only appears when the border or the header of the group box is clicked. If you click somewhere inside the box then the context menu of the parent is what's displayed.

Here's some XAML that demonstrates the problem:

<Window x:Class="Dummy.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Window.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Window menu" />
        </ContextMenu>
    </Window.ContextMenu>
    <GroupBox Header="GroupBox">
        <GroupBox.ContextMenu>
            <ContextMenu>
                <MenuItem Header="GroupBox menu" />
            </ContextMenu>
        </GroupBox.ContextMenu>
    </GroupBox>
</Window>

So when you click inside the groupbox, you always get the "Window menu" coming up, but I want the "Group menu" instead.

Does anyone know why this is happening and potentially how I go about resolving it?

Many thanks.

OJ

A: 

The group box is essentially an empty border with a header label. In the case that there is no content in the group box, your clicks are actually landing on the owning Window, which explains why "Window menu" is coming up. If you put some content into the group box which fills it entirely, you will see the group box context menu come up at all times:

<GroupBox Header="GroupBox">
   <GroupBox.ContextMenu>
        <ContextMenu>
            <MenuItem Header="GroupBox menu"/>
        </ContextMenu>
    </GroupBox.ContextMenu>
    <Label HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/> 
</GroupBox>
Charlie
Thanks Charlie. What you said makes sense. The funny thing is that in my actual code (not the fudged example above) I do have content, but that content isn't a simple label as you showed above. Are there only certain types of content that this stuff works with? I have a DockPanel which fills the entire group box, but that doesn't seem to help. Perhaps I'll throw a border in there and see how that goes.Thanks for your suggestion.
OJ
Hi again. So it appears that only certain types of content actually make this functionality work. Things like dockpanels and borders just dont work at all. So I wrapped the entire content in a label, as per your suggestion, and that fixed the issue. I don't like it, but it works :) Many thanks.
OJ