如何进行事件以更改定制属性(定制控件) [英] How to make events for changing custom made properties (custom control)

查看:129
本文介绍了如何进行事件以更改定制属性(定制控件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有从TextBox类继承的自定义控件,并且我添加了一些属性,例如,我具有placeHolderText属性,并且我想拥有一些在更改文本时会发生的事件?

像这些事件一样




而且在设计器视图$ b中有我的财产$ b




如何实现?

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?

推荐答案

要在C#中创建事件,您可以遵循标准.NET事件模式

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

某物属性创建 Changed 事件自定义控件,您可以按照以下步骤操作:

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


  • 声明一个事件 SomethingChanged 。它可以是任何委托,作为一般委托,您可以依靠 EventHandler 委托或 EventHandler< T> 您想要一个特定的事件参数,而不是使用 EventArgs

  • 创建受保护的虚拟 OnSomethingChanged 方法,该方法接受事件args并负责引发事件。因此,如果使用此方法,则应在正文中引发事件。

  • 在属性设置器中,检查该值是否与当前值不同,进行分配,然后调用 OnSomethingChanged 引发事件。

  • 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.

示例

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

这篇关于如何进行事件以更改定制属性(定制控件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆