How to make events for changing custom made properties (custom control)

我怕爱的太早我们不能终老 提交于 2019-12-25 03:06:54

问题


I have custom control inheriting from TextBox class , and i have added some properties , for example i have property placeHolderText and i want to have some event which will occur when i change that text?
Like these events

And there is my property in designer view

How to achieve that?


回答1:


To create an event in C# you can follow Standard .NET event patterns.

To create a Changed event for a Something property of a custom control, you can follow these steps:

  • Declare an event SomethingChanged. It can be any delegate, as a general delegate you can rely on EventHandler delegate or EventHandler<T>, in case which you want to have a specific event argument rather than using EventArgs.
  • Create a protected virtual OnSomethingChanged method which accepts the event args and is responsible to raising the event. So you should raise the event in body if this method.
  • In the property setter, check if the value is different from current value, assign it and call OnSomethingChanged to raise the event.

Example

public EventHandler PlaceHolderChanged;
string placeholder;
public string PlaceHolder
{
    get { return placeholder; }
    set
    {
        if (placeholder != value)
        {
            placeholder = value;
            OnPlaceHolderChanged(EventArgs.Empty);
        }
    }
}
protected virtual void OnPlaceHolderChanged(EventArgs e)
{
    PlaceHolderChanged?.Invoke(this, e);
}


来源:https://stackoverflow.com/questions/51004364/how-to-make-events-for-changing-custom-made-properties-custom-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!