简体   繁体   中英

How to detect C# control name changed?

我使用C#Windows窗体控件库创建了一个复合控件,当我在测试程序中使用新控件时,我想找到一种方法来检测新控件的名称何时在设计时更改了,我该怎么办?

You can use the IComponentChangeService (in System.ComponentModel.Design ) like in this example:

public class MyControl : UserControl
{
    public event EventHandler NameChanged;
    protected virtual void OnNameChanged()
    {
        EventHandler handler = NameChanged;
        if (handler != null) handler(this, EventArgs.Empty);
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        IComponentChangeService changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
        if (changeService == null) return; // not provided at runtime, only design mode

        changeService.ComponentChanged -= OnComponentChanged; // to avoid multiple subscriptions
        changeService.ComponentChanged += OnComponentChanged;
    }

    private void OnComponentChanged(object sender, ComponentChangedEventArgs e)
    {
        if (e.Component == this && e.Member.Name == "Name")
            OnNameChanged();            
    }
}

This service is only provided in design mode, not at runtime.
I unsubscribe and subscribe again to the ComponentChanged event (to avoid multiple subscriptions).

In the event handler OnComponentChanged I check if my name has changed and raise the NameChanged event.

There is no event "OnNameChanged" and the Name-Property itself is not virtual and therefore not overrideable... I'm afraid, that there is no sure way...

Some suggestions:

  • Define your own Name-Property with "new", but inherited classes will not automatically overtake this and - even worse - casts to Control and usage of Control.Name will just work around your property...

  • Define a virtual "MyName"-Property and use this only to write through onto the Control's Name-Property. Still a call on Control.Name will fly by, but at least you can enforce the usage of MyName...

  • Puffer the Name within your constructor and define a Timer to look regularely if something has changed

Alltogether I must admit, that I would not use any of those... I don't know what exactly you want to achieve, but I'd try to find a different approach to reach this goal...

public MyControl : UserControl
{
     public new string Name 
     {
         get  { return base.Name; }

         set  
         {
            base.Name = value;

            // handle the name change here....
         }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM