[英]C# WPF Array of Buttons, Button Coordinates
我在窗口的主网格中创建了一个按钮矩阵,并且还为每个按钮创建了一个事件。 我也有一个包含每个按钮的某些属性的整数矩阵(例如,int a [1,2]是按钮btn [1,2]的属性)。 我正计划创建一个类似迷宫的东西,在上面只能通过跳骑士(从国际象棋的方式)从一个按钮传递到另一个按钮。我不知道如何找到被按下按钮的坐标,以便我可以改变位置当前按钮的
Button[,] btn = new Button[25, 25];
for (x = 5; x <= n; x++)
{
for (y = 5; y <= n; y++)
{
btn[x, y] = new Button();
left += 72;
btn[x,y].Margin =new Thickness(left,top,0,0);
btn[x,y].Height = 32;
btn[x,y].Width = 32;
btn[x, y].Click += new RoutedEventHandler(btn_Click);
if (a[x, y] == 2)
btn[x,y].Background = Brushes.Red;
else
btn[x,y].Background = Brushes.Blue;
main.Children.Add(btn[x, y]);
}
left = 0;
top += 72;
}
}
private void btn_Click(object sender, RoutedEventArgs e)
{
}
我只是想出一个疯狂的主意...为什么不制作自己的Button
并命名为MazeButton
东西? 从Button
派生并添加一些属性,以利用继承。
public class MazeButton : System.Windows.Controls.Button {
private int left;
private int top;
//rest of implementation
}
这样,您可以将迷宫中按钮所在的信息直接传递到按钮中。 您可以定义自定义事件以及您想要的任何其他内容。
尝试这个:
private void btn_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Buttonl;
if(btn!=null)
{
Point renderedLocation = btn.TranslatePoint(new Point(0, 0), this);
}
else
{
//you may throw an exception if you want.
}
}
这是问题的另一个解决方案。 我将每个按钮存储在元组列表中而不是数组中,然后我搜索包含Linq的按钮中的元组。
假设您使用的是.NET4。否则,可以编写Tuple类(可以在SO上找到它)。
private List<Tuple<Button, Int32, Int32>> listButton;
private void SetButtons()
{
// TODO define what is n, left, top
listButton = new List<Tuple<Button, int, int>>();
for (int x = 5; x <= n; x++)
{
for (int y = 5; y <= n; y++)
{
Button btn = new Button();
left += 72;
btn.Margin = new Thickness(left, top, 0, 0);
btn.Height = 32;
btn.Width = 32;
btn.Click += new RoutedEventHandler(btn_Click);
if (a[x, y] == 2)
btn.Background = Brushes.Red;
else
btn.Background = Brushes.Blue;
listButton.Add(new Tuple<Button, int, int>(btn, x, y));
main.Children.Add(btn);
}
left = 0;
top += 72;
}
}
private void btn_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
var tuple = listButton.Where(t => t.Item1 == button).FirstOrDefault();
if (tuple != null)
{
Int32 x = tuple.Item2;
Int32 y = tuple.Item3;
// Do whay you want this x and y found
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.