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

筅森魡賤 提交于 2019-12-08 02:16:08

问题


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

    }

回答1:


Use a delegate or a lambda expression.

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



回答2:


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.




回答3:


   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.



来源:https://stackoverflow.com/questions/5652515/how-can-i-pass-addition-local-object-variable-to-my-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!