Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a header for a context menu that the user cannot select

Tags:

c#

wpf

xaml

I am trying to add a header to a context menu. The xaml below almost does what I need. The problem is that the user can select the TextBlock and if they click the Textblock the menu vanishes. (If the user clicks the Separator the menu remains.) So basically I want the TextBlock not to be highlighted if the user moves their mouse over it and I also don't want the menu to vanish if the user clicks the TextBlock.

<TextBlock.ContextMenu>
    <ContextMenu>
        <TextBlock Text="Test!!!" />
        <Separator></Separator>
        <MenuItem Header="menu item1" />
        <MenuItem Header="menu item2" />
    </ContextMenu>
</TextBlock.ContextMenu>
like image 457
ashlar64 Avatar asked Aug 21 '14 15:08

ashlar64


2 Answers

You can use a custom template on your separator to achieve what you want

<TextBlock.ContextMenu>
    <ContextMenu>
        <Separator>
            <Separator.Template>
                <ControlTemplate TargetType="Separator">
                    <StackPanel>
                        <TextBlock Text="Test!!!" />
                        <Separator/>
                    </StackPanel>
                </ControlTemplate>
            </Separator.Template>
        </Separator>
        <MenuItem Header="menu item1" />
        <MenuItem Header="menu item2" />
    </ContextMenu>
</TextBlock.ContextMenu>

This way the text is not responding to clicks or hovers and keeps the menu open, plus you can reuse if you turn the template into a ressource.

like image 91
rmtz Avatar answered Sep 25 '22 00:09

rmtz


If you just want to add some space above the Separator in your ContextMenu, then it is customary to use the Margin property. As there are four input values, we just need to set only the 'up' value. Try this:

<TextBlock Text="{Binding SomeTextField}">
    <TextBlock.ContextMenu>
        <ContextMenu>
            <Separator Margin="0,25,0,0"></Separator>
            <MenuItem Header="menu item1" />
            <MenuItem Header="menu item2" />
        </ContextMenu>
    </TextBlock.ContextMenu>
</TextBlock>
like image 42
Sheridan Avatar answered Sep 26 '22 00:09

Sheridan