views:

9

answers:

1

I want to create a UserControl with several controls inside. These controls should behave simmilar to the radio buttons, i. e., the status of one of them affects the status of the rest. To do that I would like to be able to handle the OnClick event on each of the controls from the parent.

One solution could be to call a method of the parent, to perform the global UserControl change, from the child controls' OnClick method. Something like:

class Child : UserControl
{
    ...

    protected override void OnClick(EventArgs z_args)
    {
       // do own stuff

       ((PartentType)Parent).ChangeStatus(this);
    }

    ...
}

This is a solution, but I wonder if there is a more standard an elegant way to solve this issue. Thanks!

+2  A: 

No, this is very bad, a control should never depend on having a specific parent. Do it the same way any Windows Forms control does it: if something interesting happens that a parent might be interested in then raise an event:

    public event EventHandler StatusChanged;

    public int Status {
        get { ... }
    }

    protected override void OnClick(EventArgs z_args) {
        // do own stuff
        //...
        var handler = StatusChanged;
        if (handler != null) handler(this, EventArgs.Empty);
    }

Consider putting the event raising code in a private setter for the Status property.

Hans Passant