我有几个按钮,我把它们放在wrapPanel in循环中:
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);
}
}我想知道哪个按钮被点击了,并为每个按钮做了一些不同的事情。例如,我会有一个方法
private void buttonClicked(Button b)在我发送点击按钮的地方,检查它的类型、名称或id,然后做一些事情。这有可能吗?
发布于 2012-07-27 20:22:30
将此代码添加到您的循环中:
bnt.Click += (source, e) =>
{
//type the method's code here, using bnt to reference the button
};Lambda表达式允许您在代码中嵌入匿名方法,以便您可以访问本地方法变量。你可以在here上阅读更多关于它们的信息。
发布于 2012-07-27 20:22:51
所有连接到事件的方法都有一个参数sender,它是触发事件的对象。因此,在您的示例中,发送者是被单击的Button对象。您可以像这样将其转换为:
void button_Click(Object sender, EventArgs e)
{
Button buttonThatWasClicked = (Button)sender;
// your code here e.g. call your method buttonClicked(buttonThatWasClicked);
}发布于 2012-07-27 20:33:45
再次感谢你的两次回复--两次都很有效。这里有完整的代码,也许其他人将来会需要它。
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);
}顺便问一下,我想知道是否可以(使用wrapPanel)将按钮移动到另一个位置?我的意思是我什么时候会点击并拖动按钮就能做到这一点呢?
https://stackoverflow.com/questions/11687633
复制相似问题