Landon Conway Landon Conway - 3 months ago 24
C# Question

C# Event handler for custom string property for a UserControl?

I created a custom User Control in C# and I added a custom Text property for my control. However I would also like raise an even whenever the value of my Text Property is changed and I want to call it

TextChanged
.

Here is my code for the property I created for my user control:

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


As you see I already created the
TextChanged
Event Handler but I don't know how to link it to the
Text
Property to make it to where when the value of 'Text' changes, the event will be raised.

Please be aware that I am using Windows Forms and I am not using WPF and I do not want to have to do anything that requires WPF. Every solution I have found for this issue has something to do with WPF or it does not completely solve my issue because they are not trying to create an event handler for a string. I don't understand how other people manage to do this but I would like to know how. Thanks.

Answer

You should call the event handler delegate manually in the setting of the Text property.

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