UserControl 的自定义文本 属性 的 C# 自定义 TextChanged 事件处理程序?

C# custom TextChanged event handler for custom Text property for a UserControl?

我在 C# 中创建了一个自定义用户控件,并为我的控件添加了一个自定义文本 属性。但是,每当我的 Text 属性 的值发生变化并且我想将其命名为 TextChanged.

时,我也想提出一个偶数

这是我为用户控件创建的 属性 代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestControls
{
    public partial class Box: UserControl
    {
        public Box()
        {
            InitializeComponent();
        }

        [Bindable(true)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [Browsable(true)]
        [Category("Appearance")]
        public override string Text { get { return base.Text; } set { base.Text = value; this.Invalidate(); } }

        [Browsable(true)]
        public event EventHandler TextChanged;
    }
}

如您所见,我已经创建了 TextChanged 事件处理程序,但我不知道如何将其 link 到 Text 属性 使其到达哪里当'Text'的值改变时,将引发该事件。

请注意,我使用的是 Windows 表单,我没有使用 WPF,我不想做任何需要 WPF 的事情。我为这个问题找到的每个解决方案都与 WPF 有关,或者它没有完全解决我的问题,因为他们没有尝试为字符串创建事件处理程序。我不明白其他人是如何做到这一点的,但我想知道如何做到这一点。谢谢。

您应该在 Text 属性 的设置中手动调用事件处理程序委托。

public partial class Box : UserControl
{
    public Box()
    {
        InitializeComponent();
    }

    [Bindable(true)]
    [EditorBrowsable(EditorBrowsableState.Always)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    [Browsable(true)]
    [Category("Appearance")]
    public override string Text
    {
        get { return base.Text; }
        set
        {
            if (base.Text != value)
            {
                base.Text = value; this.Invalidate();
                if(TextChanged != null)
                    TextChanged(this, EventArgs.Empty)
            }
        }
    }

    [Browsable(true)]
    public event EventHandler TextChanged;
}

如果你只是想处理 TextChanged 事件,你不需要做任何事情,UserControl class 有 TextChanged 可以正常工作。但它不可浏览,就像它的 Text 属性。

如果您想使其可浏览,作为其他答案的替代方案,您可以通过这种方式使用自定义事件访问器(事件属性):

[Browsable(true)]
public event EventHandler TextChanged
{
    add { base.TextChanged += value; }
    remove { base.TextChanged -= value; }
}

要了解有关语法的更多信息,请查看此 MSDN 资源: