第一次设置文本时,子类 RichTextBox OnTextChange 事件不会触发
Subclassed RichTextBox OnTextChange event doesn't fire when text first set
我已经将 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
文件中编辑它!
我会试试这个(我只在 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);
}
}
}
我已经将 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
文件中编辑它!
我会试试这个(我只在 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);
}
}
}