如何自定义默认上下文菜单

3
在我的 WPF 应用程序中,我希望使所有文本框的剪切、复制和粘贴受限。
一种方法是设置 ContextMenu ="{x:Null}"
但是这样做会失去拼写检查建议,而我不想失去它们。此外,在我的应用程序中,我有1000个文本框,所以我希望以更优化的方式实现此功能。
任何建议都将不胜感激。
1个回答

1
如果您只需要与拼写检查相关的菜单项,可以参考此MSDN文章:
如何:使用上下文菜单进行拼写检查
如果您想将自定义ContextMenu应用于多个(但不是所有)文本框:
  <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>

如果您想将自定义上下文菜单应用于所有文本框:
  <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>


注意:

  1. 您可以将上下文菜单资源移动到应用程序级别,而不是窗口级别。
  2. MSDN文章提到通过C#代码获取菜单项,而不是通过XAML。我可以轻松地将“全部忽略”命令转换为XAML(见上方的代码片段),但对于拼写建议,您需要进行一些研究和开发。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接