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

标签 c# winforms user-controls event-handling

我在 C# 中创建了一个自定义用户控件,并为我的控件添加了一个自定义文本属性。但是,每当我的文本属性的值发生更改并且我想将其称为 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 事件处理程序,但我不知道如何将它链接到 Text 属性以使其在'文本'改变,事件将被引发。

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

最佳答案

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

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;
}

关于UserControl 的自定义 Text 属性的 C# 自定义 TextChanged 事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38965960/

相关文章:

c# - 为什么我无法编译在 C# 的类接口(interface)中声明的自定义事件

c# - 使用全屏 View 作为幻灯片的 WPF 幻灯片

c# - 调用目标抛出异常 - 在 Visual Studio 中执行 .dtsx 文件时

c# - 执行处理程序 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper' 的子请求时出错

wpf - Windows 窗体死了。 WPF的长生命周期

interop - 使用 VS.NET 构建 OCX?

ASP.Net MVC "logged in" View /标记最佳实践

c# - 在 Window 应用程序中用 C# 打开 Pdf 文档

C# 如何在无法在命名空间中包含 System.Linq 的情况下将 FirstOrDefault 与数组一起使用?

c# - 我怎样才能使 WinForms TabPage 标题宽度适合它的标题?