如何将单击事件和名称设置为动态创建的按钮数组
本文关键字:动态 创建 数组 按钮 设置 单击 事件 | 更新日期: 2023-09-27 18:03:03
我为《扫雷游戏》创建了8*8的按钮矩阵。我需要设置点击事件和名称给他们。我该怎么做呢?请帮助。我也用画布来创建网格。这是最好的方法吗?
private void makeGrid()
{
int firstlp,secondlp,position=50;
for (int i = 0; i < 400; i=i+50)
{
for (secondlp = 0; secondlp < 400; secondlp = secondlp + 50)
{
Button lbl = new Button()
{
Content = "",
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Center,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Height = 50,
Width = 50,
};
jereMy.Children.Add(lbl);
Canvas.SetLeft(lbl, secondlp + 50);
Canvas.SetRight(lbl, secondlp + 50);
Canvas.SetTop(lbl, position);
}
position = position + 50;
}
}
您可以在创建按钮时添加EventHandler和名称:
lbl.Click += button_Click;
lbl.Name = string.Format("btn_{0}_{1}",i,secondlp);
eventandler应该是这样的:
private void button_Click ( object sender, RoutedEventArgs e )
{
// Handle the click event
}
我建议用UniformGrid
代替Canvas
。您可以使用属性Rows
和Columns
使UnformGrid 8x8。WPF中有很多布局面板,我认为它们中的大多数比Canvas更适合你的需求。(例如Grid
或嵌套StackPanel
s)
您可以像下面这样添加一个事件注册。
lbl.Click+= OnButtonClick(sender,e);
private void OnButtonClick(object sender, EventArgs e)
{
//To do.
}