Reputation: 158
I created a composite control using C# Windows Forms Control Library, when I use the new control in a test program, I want to find a way to detect when did the name of new control changed at design time, what should I do?
Upvotes: 0
Views: 1351
Reputation: 43936
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.
Upvotes: 2
Reputation: 2940
public MyControl : UserControl
{
public new string Name
{
get { return base.Name; }
set
{
base.Name = value;
// handle the name change here....
}
}
}
Upvotes: -1
Reputation: 67331
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...
Upvotes: 0