用于 UserControl 的自定义 Text 属性的 C# 自定义 TextChanged 事件处理程序?

Lan*_*way 3 c# user-controls event-handling winforms

我在 C# 中创建了一个自定义用户控件,并为我的控件添加了一个自定义文本属性。不过,每当我的 Text 属性的值发生更改并且我想调用它时,我也想引发一个 Even 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我已经创建了TextChanged事件处理程序,但我不知道如何将其链接到Text属性,以便当“文本”的值发生变化时,将引发事件。

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

Nic*_*ico 5

您应该在属性设置中手动调用事件处理程序委托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;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你只是想处理`TextChanged`事件,你不需要做任何事情,`UserControl`类有`TextChanged`可以正常工作。但它不可浏览,就像它的“Text”属性一样。如果您想让它可浏览,您可以使用自定义事件访问器(事件属性)作为替代方案。 (2认同)