tags:

views:

43

answers:

3

In .NET C# 3.5 Winforms, I have a user control with some simple child controls such as textboxes, labels, and buttons. Currently when I set the .Enabled property of the user control to false, the controls dim accordingly. However, if I use a custom .BackColor for the user control, sometimes the dimming is not as apparent as I would prefer.

Is there a way to specify or change the dimming color of the user control when .Enabled is set to false? Or on a related note, is there a way I can call a method when this happens?

+1  A: 

Controls have an EnabledChange event you can tap into. Create a handler for this event for the user control and change its controls' properties accordingly.

Anthony Pegram
Thanks, this actually would have been perfect but because I re-use the user control in several places, I wanted to handle the state change within the user control code (rather than through an event). I posted my answer to this also.
JYelton
@JYelton, the user control can subscribe to its own events. The user control would be the one responding to the EnabledChanged event in that case.
Anthony Pegram
Self-subscribing was thinking "outside the box" for me. Thanks for pointing it out!
JYelton
A: 

I wound up overriding the base property of the user control, because I wanted the code that handles the state change to be in the user control itself (rather than subscribing to an event).

This is what I did:

public new bool Enabled
{
    get
    {
        return base.Enabled;
    }
    set
    {
        base.Enabled = value;
        // code to alter the appearance of control
    }
}

EDIT:

The suggestion of self-subscribing to the even within the user control seemed much cleaner than hiding the non-virtual Enabled property. Further edits to other answers gave me this better solution:

this.EnabledChanged += new EventHandler(UserControl_EnabledChanged);
void UserControl_EnabledChanged(object sender, EventArgs e)
{
    // code to alter appearance of control
}
JYelton
+1  A: 

You can override .OnEnabledChanged(EventArgs e) method if you dont want to subscribe to EnabledChanged event, and it's a better solution than hiding Control's .Enable property, which is not marked virtual:

protected override OnEnabledChanged(EventArgs e)
{
    base.OnEnabledChanged(e);
    // your code here
}
max
Max, this was much better than hiding the `.Enable` property, thank you. Anthony's suggestion of having the user controls self-subscribe to the event was what I preferred.
JYelton