Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: How to style or disable the default ContextMenu of a TextBox

Tags:

.net-3.5

wpf

xaml

Apparantly when users right-click in our WPF application, and they use the Windows Classic theme, the default ContextMenu of the TextBox (which contains Copy, Cut and Paste) has a black background.

I know this works well:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">    <TextBox ContextMenu="{x:Null}"/>  </Page> 

But this doesn't work:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">  <Page.Resources>   <Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">    <Setter Property="ContextMenu" Value="{x:Null}"/> </Style> </Page.Resources>    <TextBox/> </Page>  

Does anyone know how to style or disable the default ContextMenu for all TextBoxes in WPF?

like image 960
Arcturus Avatar asked Aug 13 '08 10:08

Arcturus


Video Answer


2 Answers

To style ContextMenu's for all TextBoxes, I would do something like the following:

First, in the resources section, add a ContextMenu which you plan to use as your standard ContextMenu in a textbox.
e.g.

<ContextMenu x:Key="TextBoxContextMenu" Background="White">   <MenuItem Command="ApplicationCommands.Copy" />   <MenuItem Command="ApplicationCommands.Cut" />   <MenuItem Command="ApplicationCommands.Paste" /> </ContextMenu> 

Secondly, create a style for your TextBoxes, which uses the context menu resource:

<Style TargetType="{x:Type TextBox}">   <Setter Property="ContextMenu" Value="{StaticResource TextBoxContextMenu}" /> </Style> 

Finally, use your text box as normal:

<TextBox /> 

If instead you want to apply this context menu to only some of your textboxes, do not create the style above, and add the following to your TextBox markup:

<TextBox ContextMenu="{StaticResource TextBoxContextMenu}" /> 

Hope this helps!

like image 193
Brad Leach Avatar answered Sep 18 '22 17:09

Brad Leach


Bizarre. ContextMenu="{x:Null}" doesn't do the trick.

This does, however:

<TextBox.ContextMenu>     <ContextMenu Visibility="Collapsed">     </ContextMenu> </TextBox.ContextMenu> 
like image 22
Robin Davies Avatar answered Sep 17 '22 17:09

Robin Davies