代表和活动

时间:2013-02-18 11:30:52

标签: c# events delegates

我有两种形式。

Form1中:

public partial class Panel1
    {
        public void ShowExport(object sender, EventArgs e)
        {
           .......
        }
    }

Form2:

public partial class Panel2
{
        public delegate void ShowExportReport(object sender, EventArgs e);
        public event ShowExportReport ShowExportClicked;

private void buttonExport_Click(object sender, RoutedEventArgs e)
        {         
           if (ShowExportClicked != null)
            {
                ShowExportClicked(sender, new EventArgs());
            }                     

        }
}

点击按钮 -

button.Click = buttonExport_Click

如何从 Panel2.buttonExport_Click 调用 Panel1.ShowExport()

5 个答案:

答案 0 :(得分:2)

在Panel1中,您必须订阅事件:

pnl2.ShowExportClicked += new ShowExportReport(ShowExport);

答案 1 :(得分:2)

您需要将Panel 1类中的事件ShowExportClicked的处理程序分配给Panel 2类对象。

     public partial class Panel1
        {
            Panel2 pnl2;
            public Panel1()
            {
               pnl2 = new Panel2();
               pnl2.ShowExportClicked += new ShowExportReport(ShowExport);    
            }

            public void ShowExport(object sender, EventArgs e)
            {
               .......
            }
        }

答案 2 :(得分:0)

pnl2.ShowExportClicked += ShowExport;

答案 3 :(得分:0)

在Form1上创建您的活动。并在Form2中听取事件。

Form1中:

public event EventHandler ShowExportChanged;

private void ShowExportChanged()
{
    var handler = ShowExportChanged;
    if(handler == null)
        return;

    handler(this, EventArgs.Empty);
}

public void ShowExport(object sender, EventArgs e)
{
  ShowExportChanged();
}

窗体2:

pnl1.ShowExportChanged+= new OnShowExportChanged(ShowExportChanged);

答案 4 :(得分:0)

  

如何从Panel2.buttonExport_Click?

调用Panel1.ShowExport()

在实例化form2时从form1传递(仅必要的)信息。

Form1.cs中:

void ShowForm2_Click()
{
    var form2 = new Form2();
    form2.ShowExportClicked += ShowExport;
    form2.Show();
}

现在,从Form2开始,您只需点击按钮即可拨打ShowExport