JYelton
JYelton

Reputation: 36522

Changing properties on user control based on Enabled property

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?

Upvotes: 5

Views: 7753

Answers (3)

JYelton
JYelton

Reputation: 36522

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
}

Upvotes: 1

max
max

Reputation: 34427

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
}

Upvotes: 2

Anthony Pegram
Anthony Pegram

Reputation: 126932

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.

Upvotes: 5

Related Questions