WinForm用户控件属性的创建事件已更改
本文关键字:事件 创建 用户 控件 属性 WinForm | 更新日期: 2023-09-27 17:58:51
每当TextBox控件的SelectedText或SelectionStart
属性发生更改时,我都想引发一个事件。有没有什么简单的方法可以做到这一点,而不需要从头开始编写自定义TextBox控件?
显然,一种选择是让计时器检查这些属性是否有更改,但我更喜欢不使用任何计时器。
到目前为止,我已经尝试创建一个从TextBox继承并重写SelectedText属性的控件,但失败了。另外,SelectionStart
不能被覆盖。
是的,我知道RichTextBox控件具有SelectionChanged
事件。不过,我需要一个普通的TextBox,而不是RichTextBox。
我不知道如何从TextBox
实现您的目标,但下面是使用继承和自定义组件的解决方案示例。用户通过鼠标选择一些新文本后,会引发SelectionChanged
事件。
请注意,MouseDown
和MouseUp
事件以及SelectionStart
和SelectionLength
属性在TextBox
中是公共的,因此如果需要,可以避免子类化。
class CustomTextBox : TextBox
{
public event EventHandler SelectionChanged;
private int _selectionStart;
private int _selectionLength;
protected override void OnMouseDown(MouseEventArgs e)
{
_selectionStart = SelectionStart;
_selectionLength = SelectionLength;
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (null != SelectionChanged && (_selectionStart != SelectionStart || _selectionLength != SelectionLength))
SelectionChanged(this, EventArgs.Empty);
base.OnMouseUp(e);
}
}