子类化富文本框 OnTextChange 事件在首次设置文本时不会触发

本文关键字:置文本 文本 OnTextChange 事件 子类 | 更新日期: 2023-09-27 18:32:29

我已经子类化了一个RichTextBox以添加语法突出显示,并且在手动更改文本时工作正常。但是,首次在代码中设置Text时,不会触发 OnTextChanged 事件。

我拥有的事件代码是

/// <summary>
/// When text changes keywords are searched for and highlighted
/// </summary>
/// <param name="e"></param>
protected override void OnTextChanged(EventArgs e)
{
    if (highlighting)
        return;
    int currentSelectionStart = this.SelectionStart;
    int currentSelectionLength = this.SelectionLength;
    base.OnTextChanged(e);
    String text = this.Text;
    this.Text = "";
    this.HighlightSyntax(text);
    this.SelectionStart = currentSelectionStart;
    this.SelectionLength = currentSelectionLength;
}

当从代码设置文本时,我如何让此事件触发,例如 this.structureInFileTextBox.Text = obj.FileStructure; ?我已经尝试覆盖 Text 属性,但这会使 Visual Studio 崩溃,我必须从.cs文件中编辑它,然后才能再次打开项目!

子类化富文本框 OnTextChange 事件在首次设置文本时不会触发

我会尝试这个(我只在base.Text = "";中更改了this.Text = "";):

/// <summary>
/// When text changes keywords are searched for and highlighted
/// </summary>
/// <param name="e"></param>
protected override void OnTextChanged(EventArgs e)
{
    if (highlighting)
        return;
    int currentSelectionStart = this.SelectionStart;
    int currentSelectionLength = this.SelectionLength;
    base.OnTextChanged(e);
    String text = this.Text;
    base.Text = "";
    this.HighlightSyntax(text);
    this.SelectionStart = currentSelectionStart;
    this.SelectionLength = currentSelectionLength;
}

并通过以下方式覆盖文本属性:

public new string Text
{
    get { return base.Text; }
    set
    {
        if (base.Text != value)
        {
             base.Text = value;
             OnTextChanged(EventArgs.Empty);
        }
    }
}