开发者

OnClick event on compound UserControls

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 metho开发者_JAVA技巧d 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜