0

I created 8*8 matrix of button for Minesweeper Game. I need to set click event and name to them. How can I do that? Help please. Also I used canvas to create the grid. Is it the best way to do that?

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;
        }  

    }

2 Answers 2

1

You can add the EventHandler and name when creating the Button:

lbl.Click += button_Click;
lbl.Name = string.Format("btn_{0}_{1}",i,secondlp);

The EventHandler should look like this:

private void button_Click ( object sender, RoutedEventArgs e )
{
  // Handle the click event
}

And I'd suggest to use a UniformGrid instead of Canvas. You can use the properties Rowsand Columns to make the UnformGrid 8x8. There are a lot of layout panels in WPF, I think most of them fit your needs better than Canvas. (e.g. Grid or nested StackPanels)

Sign up to request clarification or add additional context in comments.

Comments

1

You can add a event registerion such as below.

lbl.Click+= OnButtonClick(sender,e);


private void OnButtonClick(object sender, EventArgs e)
{
   //To do.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.