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>
                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.
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>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With