How to customize default context menu

2019-07-20 15:21发布

In my WPF application I want to make my all textboxes cut, copy and paste restricted. One way to do this is set ContextMenu ="{x:Null}"

But by doing this I will loose the spell check suggestions which I don't want to loose. Also In my application I have 1000 textboxes so I want to do this is in a more optimize way.

Any advice will be appreciated.

1条回答
走好不送
2楼-- · 2019-07-20 15:45

If all you need is menu items related to spell checking, you can refer to this MSDN article:
How to: Use Spell Checking with a Context Menu.

If you want to apply custom ContextMenu to multiple (but not all) textboxes:

  <Window.Resources>
    <ContextMenu x:Key="MyCustomContextMenu">
      <MenuItem Header="Ignore All" Command="EditingCommands.IgnoreSpellingError" />
    </ContextMenu>
  </Window.Resources>
  <Grid>
    <TextBox Height="23" Name="textBox1" Width="120" SpellCheck.IsEnabled="True"
      ContextMenu="{StaticResource MyCustomContextMenu}" />
  </Grid>

If you want to apply custom ContextMenu to ALL textboxes:

  <Window.Resources>
    <Style TargetType="{x:Type TextBox}">
      <Setter Property="ContextMenu">
        <Setter.Value>
          <ContextMenu>
            <MenuItem
              Header="Ignore All"
              Command="EditingCommands.IgnoreSpellingError" />
          </ContextMenu>
        </Setter.Value>
      </Setter>
    </Style>
  </Window.Resources>
  <Grid>
    <TextBox Height="23" Name="textBox1" Width="120" SpellCheck.IsEnabled="True"  />
  </Grid>


NOTE:

  1. You can move the context menu resource to application level instead of the window level.
  2. The MSDN article mentions to get menu items via C# code and not via XAML. I could easily port the "Ignore All" command to XAML (code snippets above), but for spelling suggestions, you will have to do some R&D.
查看更多
登录 后发表回答