向富文本框组件添加事件

问题描述

我试图将事件添加到我每次在富文本框中创建的标签中。这是下面的代码。 在我的类MainWindowController中,我有

public static Window MainWindow = new Windows.MainWindow();
public static Pages.MainPage MainPage = new Pages.MainPage();
public static Pages.LoginPage LoginPage = new Pages.LoginPage();
public static FlowDocument ChatDocument = new FlowDocument();
public static Paragraph ChatParagraph = new Paragraph();

在另一个类中,我有方法,每次客户端通过网络收到更新状态消息时,都会调用它。

        private static void HandleStatus(string MessageString)
        {
            string Sender = AuxiliaryClientWorker.GetElement(MessageString,"-U "," -Content");
            string Message = AuxiliaryClientWorker.GetElement(MessageString,"-Content ",".");
            MainWindowController.MainWindow.dispatcher.Invoke(() =>
            {
                #region Status updater
                System.Windows.Controls.Label StatusLabel = new System.Windows.Controls.Label();
                StatusLabel.FontSize = 18;
                StatusLabel.FontStyle = FontStyles.Oblique;
                StatusLabel.FontStyle = FontStyles.Italic;
                StatusLabel.Foreground = System.Windows.Media.Brushes.Black;
                StatusLabel.Content = Sender + " has updated their status to " + Message;
                StatusLabel.MouseEnter += StatusLabel_MouseEnter;                
                #endregion
                MainWindowController.ChatParagraph.Inlines.Add(StatusLabel);
                MainWindowController.ChatParagraph.Inlines.Add(Environment.NewLine);
                MainWindowController.ChatDocument.Blocks.Add(MainWindowController.ChatParagraph);
                MainWindowController.MainPage.ClientChatTextBox.Document = MainWindowController.ChatDocument;
            });
        }

        private static void StatusLabel_MouseEnter(object sender,System.Windows.Input.MouseEventArgs e)
        {
            MessageBox.Show("This");
        }

一切正常,唯一的问题是,富文本框中的UI元素不会“监听”事件,因此事件永远不会触发。 MessageBox不显示。我尝试将dispatcher.Invoke命令添加到下面的方法中,它只是拒绝工作,并且该事件永不触发。希望大家都知道我要做什么!

TLDR:StatusLabel_MouseEnter永不触发

解决方法

您需要在RichTextBox上将IsDocumentEnabled属性设置为true。

https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.richtextbox.isdocumentenabled?view=netcore-3.1

获取或设置一个值,该值指示用户是否可以与RichTextBox中的UIElement和ContentElement对象进行交互。

richtextbox文档中的事件有点棘手。

对于某些事件,您可能还必须将控件放入BlockUIContainer中。

即使那样,有些事情还是不会像您期望的那样起作用。

点击已经具有含义,因此您可能会发现它已经在处理点击事件。使用预览事件-PreviewMouseDown和PreviewMouseUp进行此类操作。