如何在WinForms自定义控件中公开事件 [英] How to expose events in a WinForms custom control

查看:72
本文介绍了如何在WinForms自定义控件中公开事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了一个自定义控件,该控件的作用类似于带有标签的复选框的组框。想法是,一旦取消选中该复选框,组中的所有控件都将被禁用。

I've developed a custom control that acts like a group box with a check box over the group label. The idea being, once the check box is unchecked all the controls in the group are disabled.

我需要公开Check更改事件,以便在发生以下情况时可以执行外部操作需要。我还公开了Check状态已更改。

I need to expose the Check changed event so that external actions could be performed if required. I've also exposed the Check state changed.

当前,当使用该控件时,当组中的任何控件失去焦点时,它都会更改检查状态。

Currently, when the control is used it changes the check state when any of the controls in the group loose focus.

当我处理检查更改事件时,是否应该为任何外部处理程序重新触发该事件?

When I handle the check changed event, should I then re-fire the event for any external handlers?

< img src = https://i.stack.imgur.com/tzptj.jpg alt =在此处输入图片描述>

定义的事件:

/// <summary>
/// Event to forward the change in checked flag
/// </summary>
public event EventHandler CheckedChanged;

/// <summary>
/// Event to forward the change in checked state of the checkbox
/// </summary>
public event EventHandler CheckStateChanged;

事件处理程序代码:

private void chkBox_CheckedChanged(object sender, EventArgs e)
{
    // Disable the controls within the group
    foreach( Control ctrl in this.Controls )
    {
        if( ctrl.Name != "chkBox" && ctrl.Name != "lblDisplay" )
        {
            ctrl.Enabled = this.chkBox.Checked;
        }
    }

    // Now forward the Event from the checkbox
    if (this.CheckedChanged != null)
    {
        this.CheckedChanged(sender, e);
    }
}

private void chkBox_CheckStateChanged(object sender, EventArgs e)
{
    // Forward the Event from the checkbox
    if( this.CheckStateChanged != null )
    {
        this.CheckStateChanged( sender, e );
    }
}


推荐答案

您快到了。您只需向外部类中的事件处理程序注册事件即可。

You are almost there. You just have to register your event with a event handler in external class.

CheckedChanged += ExternalChkBox_CheckChanged;

private void ExternalChkBox_CheckChanged(object sender, EventArgs e)
{
    // External trigger
}

这篇关于如何在WinForms自定义控件中公开事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆