【问题标题】:add menu item to default context menu将菜单项添加到默认上下文菜单
【发布时间】:2008-10-16 23:27:19
【问题描述】:

我想在RichTextBox 的默认ContextMenu 中添加一个菜单项。

我可以创建一个新的上下文菜单,但我会丢失默认菜单中显示的拼写检查建议。

有没有办法在不重新实现所有内容的情况下添加项目?

【问题讨论】:

    标签: .net wpf contextmenu menuitem


    【解决方案1】:

    用拼写建议、剪切、粘贴等重新实现 RichTextBox 上下文菜单并不太难。

    如下连接上下文菜单打开事件:

    AddHandler(RichTextBox.ContextMenuOpeningEvent, new ContextMenuEventHandler(RichTextBox_ContextMenuOpening), true);
    

    在事件处理程序中根据需要构建上下文菜单。您可以使用以下内容重新创建现有的上下文菜单菜单项:

    私人 IList GetSpellingSuggestions() { List 拼写建议 = new List(); SpellingError spellingError = myRichTextBox.GetSpellingError(myRichTextBox.CaretPosition); 如果(拼写错误!= null) { foreach(spellingError.Suggestions 中的字符串 str) { 菜单项 mi = new MenuItem(); mi.Header = str; mi.FontWeight = FontWeights.Bold; mi.Command = EditingCommands.CorrectSpellingError; mi.CommandParameter = str; mi.CommandTarget = myRichTextBox; 拼写建议。添加(mi); } } 返回拼写建议; } 私有 IList GetStandardCommands() { List standardCommands = new List(); 菜单项项 = 新菜单项(); item.Command = ApplicationCommands.Cut; 标准命令。添加(项目); 项目 = 新菜单项(); item.Command = ApplicationCommands.Copy; 标准命令。添加(项目); 项目 = 新菜单项(); item.Command = ApplicationCommands.Paste; 标准命令。添加(项目); 返回标准命令; }

    如果有拼写错误,您可以使用以下命令创建 Ignore All:

    MenuItem ignoreAllMI = new MenuItem(); ignoreAllMI.Header = "全部忽略"; ignoreAllMI.Command = EditingCommands.IgnoreSpellingError; 忽略AllMI.CommandTarget = 文本框; newContextMenu.Items.Add(ignoreAllMI);

    根据需要添加分隔符。将它们添加到新的上下文菜单项中,然后添加闪亮的新 MenuItems。

    不过,我将继续寻找获取实际上下文菜单的方法,因为这与我将在不久的将来进行的工作有关。

    【讨论】:

    • 谢谢,唐奈尔。我认为它可能会重新实现。感谢您提供有关如何执行此操作的提示!
    • 一个非常相似的例子也可以直接在 MSDN 上找到:msdn.microsoft.com/en-us/library/…
    • @Donnelle 很抱歉迟到了,但是因为我面临着完全相同的问题(除了我的场景有一个简单的文本框)而且这个问题有 WPF 标签,你能提供一个更多“XAMLish”方式,好吗?
    • 我愿意,Yoda,但我已经 7 年没有使用 XAML 了!
    猜你喜欢
    • 2015-06-24
    • 2010-10-20
    • 1970-01-01
    • 2011-09-21
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    相关资源
    最近更新 更多