Click event for button in loop C# WPF

别说谁变了你拦得住时间么 提交于 2019-11-28 05:07:06

问题


I have couple buttons which im putting in wrapPanel in loop:

        for (int i = 0; i < wrapWidthItems; i++)
        {
            for (int j = 0; j < wrapHeightItems; j++)
            {
                Button bnt = new Button();
                bnt.Width = 50;
                bnt.Height = 50;
                bnt.Content = "Button" + i + j;
                bnt.Name = "Button" + i + j;
bnt.Click += method here ?
                wrapPanelCategoryButtons.Children.Add(bnt);
            }
        }

I want to know which button was clicked and do something different for each of them. For example ill have method

private void buttonClicked(Button b)

where ill send clicked button, check type, name or id of that and then do something. Is that possible?


回答1:


Add this to your loop:

bnt.Click += (source, e) =>
{
    //type the method's code here, using bnt to reference the button 
};

Lambda expressions allow you to embed anonymous methods in your code so that you can access local method variables. You can read more about them here.




回答2:


All methods you hook up to an event have an argument sender, it is the object, that triggered the event. So in your case sender the Button object that was clicked. You can just cast it like this:

void button_Click(Object sender, EventArgs e)
{
    Button buttonThatWasClicked = (Button)sender;
    // your code here e.g. call your method buttonClicked(buttonThatWasClicked);
}



回答3:


Thanks again for both responses - both works. There is full code maybe someone else could need that in future

    for (int i = 0; i < wrapWidthItems; i++)
    {
        for (int j = 0; j < wrapHeightItems; j++)
        {
            Button bnt = new Button();
            bnt.Width = 50;
            bnt.Height = 50;
            bnt.Content = "Button" + i + j;
            bnt.Name = "Button" + i + j;
            bnt.Click += new RoutedEventHandler(bnt_Click);
           /* bnt.Click += (source, e) =>
            {
                MessageBox.Show("Button pressed" + bnt.Name);
            };*/
            wrapPanelCategoryButtons.Children.Add(bnt);
        }
    }

}

void bnt_Click(object sender, RoutedEventArgs e)
{

    Button buttonThatWasClicked = (Button)sender;
    MessageBox.Show("Button pressed " + buttonThatWasClicked.Name);

}

By the way I'd like to know if that possible to (using wrapPanel) move buttons into another location ? I mean when i will click and drag button will be able to do that in wrappanel?



来源:https://stackoverflow.com/questions/11687633/click-event-for-button-in-loop-c-sharp-wpf

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