Search code examples
wpfxaml.net-3.5

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


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?


Solution

  • Due to a late bug report we discovered that we cannot use the ApplicationComands Cut Paste and Copy directly in a partial trusted application. Therefor, using these commands in any Commmand of your controls will do absolutely nothing when executed.

    So in essence Brads answer was almost there, it sure looked the right way i.e. no black background, but did not fix the problem.

    We decided to "remove" the menu based on Brads answer, like so:

    <ContextMenu x:Key="TextBoxContextMenu" Width="0" Height="0" />
    

    And use this empty context menu like so:

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