我已经将RichTextBox
子类化以添加语法突出显示,并且在手动更改文本时它可以正常工作。但是,在代码中首次设置OnTextChanged
时,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;
this.Text = "";
this.HighlightSyntax(text);
this.SelectionStart = currentSelectionStart;
this.SelectionLength = currentSelectionLength;
}
如何从代码设置文本时触发此事件,例如this.structureInFileTextBox.Text = obj.FileStructure;
?我试过覆盖Text
属性,但这会导致Visual Studio崩溃,我必须先从.cs
文件中编辑它才能再次打开项目!
答案 0 :(得分:1)
我会尝试这一点(我只更改了this.Text = "";
中的base.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;
}
并以这种方式覆盖Text属性:
public new string Text
{
get { return base.Text; }
set
{
if (base.Text != value)
{
base.Text = value;
OnTextChanged(EventArgs.Empty);
}
}
}