Add a title for the context menu that the user cannot select.
I am trying to add a title to the context menu. The Xaml below almost does what I need. The problem is that the user can select the TextBlock and if they click on the Textblock the menu will disappear. (If the user clicks on the Separator, the menu stays.) So basically I want the TextBlock not to be highlighted if the user clicks on it, and I also don't want the menu to disappear if the user clicks on the TextBlock.
<TextBlock.ContextMenu>
<ContextMenu>
<TextBlock Text="Test!!!" />
<Separator></Separator>
<MenuItem Header="menu item1" />
<MenuItem Header="menu item2" />
</ContextMenu>
</TextBlock.ContextMenu>
source to share
You can use custom template on your delimiter 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 does not respond to clicks or freezes and keeps the menu open, and can also be reused if you turn the template back into original text.
source to share
try it
<Style TargetType="{x:Type ContextMenu}">
<Setter Property="SnapsToDevicePixels"
Value="True" />
<Setter Property="OverridesDefaultStyle"
Value="True" />
<Setter Property="Grid.IsSharedSizeScope"
Value="true" />
<Setter Property="HasDropShadow"
Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContextMenu}">
<Border x:Name="Border" Background="White" BorderThickness="1" BorderBrush="Gray">
<StackPanel>
<TextBlock Text="Test!!!!"/>
<Separator></Separator>
<StackPanel IsItemsHost="True"
KeyboardNavigation.DirectionalNavigation="Cycle" />
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="HasDropShadow"
Value="true">
<Setter TargetName="Border"
Property="Padding"
Value="0,3,0,3" />
<Setter TargetName="Border"
Property="CornerRadius"
Value="4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
source to share
If you just want to add the space above Separator
in ContextMenu
then usually use the property Margin
. Since there are four inputs, we just need to set the value to "up" only. Try the following:
<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>
source to share