如何将附加本地对象变量传递给我的事件处理程序?

发布于 2024-11-01 15:59:12 字数 345 浏览 2 评论 0原文

我想将本地对象传递给事件处理程序。我怎样才能做到这一点?例如,如何在事件处理函数“hyperlinkBut​​ton_Click”中引用在下面的主函数中声明的“graphic”对象?

    void main()
    {
        Graphic graphic = new Graphic();

        hyperlinkButton.Click+=new RoutedEventHandler(hyperlinkButton_Click);
    }

    void hyperlinkButton_Click(object sender, EventArgs e)
    {

    }

I want to a pass local object to the event handler. How can I do that? For example, how can I reference the "graphic" object, which is declared in the main function below, in the event handler function "hyperlinkButton_Click"?

    void main()
    {
        Graphic graphic = new Graphic();

        hyperlinkButton.Click+=new RoutedEventHandler(hyperlinkButton_Click);
    }

    void hyperlinkButton_Click(object sender, EventArgs e)
    {

    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

柳若烟 2024-11-08 15:59:12

使用委托或 lambda 表达式。

hyperlinkButton.Click += (sender, e) => HandleGraphic(graphic, sender, e);

Use a delegate or a lambda expression.

hyperlinkButton.Click += (sender, e) => HandleGraphic(graphic, sender, e);
晨敛清荷 2024-11-08 15:59:12

您可以尝试关闭 graphic 变量:

void main()
{
    Graphic graphic = new Graphic();

    hyperlinkButton.Click += (sender, e) => 
    {
        graphic.Blah(); 
    };
}

如果您最终需要手动删除事件处理程序,这不是一个好主意。或者,您可以将 graphic 设置为字段而不是局部变量。

You could try closing on the graphic variable:

void main()
{
    Graphic graphic = new Graphic();

    hyperlinkButton.Click += (sender, e) => 
    {
        graphic.Blah(); 
    };
}

This would not be a good idea if you eventually need to remove the event handler manually. Alternatively, you could make graphic a field instead of a local variable.

笑红尘 2024-11-08 15:59:12
   void main()
    {
        Graphic graphic = new Graphic();
        hyperlinkButton.Tag = graphic;
        hyperlinkButton.Click+=new RoutedEventHandler(hyperlinkButton_Click);
    }

    void hyperlinkButton_Click(object sender, EventArgs e)
    {
       Graphic graphic =(sender as HyperlinkButton).Tag as Graphic;
    }

但不是好办法。

   void main()
    {
        Graphic graphic = new Graphic();
        hyperlinkButton.Tag = graphic;
        hyperlinkButton.Click+=new RoutedEventHandler(hyperlinkButton_Click);
    }

    void hyperlinkButton_Click(object sender, EventArgs e)
    {
       Graphic graphic =(sender as HyperlinkButton).Tag as Graphic;
    }

but not good way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文