创建自定义事件以隐藏控件不起作用

时间:2013-11-29 03:08:51

标签: c# events

以下是我的userControl

中的代码
public partial class UserControlHomeScreen : UserControl
{
    public event EventHandler SomethingHappened;

    public void DoSomething()
    {
        EventHandler handler = SomethingHappened;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }

    public void HandleEvent(object sender, EventArgs args)
    {
        MessageBox.Show("Wafak.");
    }

    public UserControlHomeScreen()
    {
        InitializeComponent();
    }

    private void btnAverageDailyBal_Click(object sender, EventArgs e)
    {
        this.Tag = 0;
        this.Hide();
    }

    private void btnComputeTransferPricing_Click(object sender, EventArgs e)
    {
        this.Tag = 1;
        this.Hide();
    }
}

这是我主要表单中的代码

private void HomeScreen()
    {
        uHomeScreen = new UserControlHomeScreen();
        uHomeScreen.Dock = DockStyle.Fill;  
        //uHomeScreen.Disposed += new EventHandler(uHomeScreen_Disposed);
        uHomeScreen.SomethingHappened += new EventHandler(uHomeScreen_SomethingHappened);
        panelMain.Controls.Add(uHomeScreen);
    }

    void uHomeScreen_SomethingHappened(object sender, EventArgs e)
    {
        MessageBox.Show("throw new NotImplementedException();");
    }

我想要发生的是,当用户控件被隐藏时,我想在我的主窗体中触发一个事件但是不起作用,我缺少什么?请帮忙。谢谢!

1 个答案:

答案 0 :(得分:1)

您的事件提升者(DoSomething)的命名约定令人困惑,您的代码不会调用DoSomething(或引发事件SomethingHappened),那么它怎么能为您解雇?在用户控件类中添加以下代码:

//override the OnVisibleChanged
protected override void OnVisibleChanged(EventArgs e){
  if(!Visible) DoSomething();
}