开发者

How can I pass addition local object variable to my event handler? [duplicate]

开发者 https://www.devze.com 2023-02-24 04:42 出处:网络
This question already has answers here: Pass extra parameters to an event handler? 开发者_开发知识库
This question already has answers here: Pass extra parameters to an event handler? 开发者_开发知识库 (10 answers) Closed 9 years ago.

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)
    {

    }


Use a delegate or a lambda expression.

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


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.


   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.

0

精彩评论

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