问题
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 onEventHandler
delegate orEventHandler<T>
, in case which you want to have a specific event argument rather than usingEventArgs
. - 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