Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am making a battleship game and I am having trouble of placing my ships which are buttons onto a grid filled with 10 by 10 buttons. In the first click event I click on a button from the stackpanel which I am selecting from. In the second I am clicking on my grid to place the button(ship) after I have selected a ship as I do in the first click. The first click events are hooked up to the stackpanel and the second ones are to the grid. After clicking on a button in the stack panel I then click on a spot in the grid and for the button I clicked in the stack panel to be assigned to the spot on the grid. This is the code I have so far for when I click on a button in the stack panel to place on the grid of buttons.
private void Button_Click(object sender, RoutedEventArgs e)
   {
       foreach (var button in myStack.Children)
       {
           if (button is Button)
           {
               (button as Button).Background = Brushes.Green;
           }

       }
       (sender as Button).Background = Brushes.Red;

   }


and this is the function where I click on my own grid after I supposedly click on the Button in the stack panel and am placing it onto the 10X10 grid. Thanks!


private void ButtonMe_Click(object sender, RoutedEventArgs e)
       {
         for (int i = 0; i < row; i++)
       {
           for (int j = 0; j < col; j++)
           {
               if(sender is Button)
               {

               }
           }
       }
           ((Button)sender).Background = Brushes.Red;
       }


What I have tried:

I have tried to connect the first button click on the stack panel to the second of placing it onto the grid with what I have written though it has not worked.
Posted
Updated 15-Dec-22 18:59pm
Comments
BillWoodruff 16-Dec-22 0:51am    
why not learn to use WPF drag and drop ?

https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/walkthrough-enabling-drag-and-drop-on-a-user-control

what grid control are you using ?

https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/drag-and-drop-overview?view=netframeworkdesktop-4.8

1 solution

I don't know how comfortable you are with WPF but another solution to your problem would be to create a Canvas. In your code you could do a hit test and determine the position of the hit, in what grid so to speak and draw a circle, or color one in or something to indicate a hit or no.

This might be a good place to start;
Canvas Class[^]
Hit testing in visual layer[^]
improve-hit-testing-in-the-visual-layer-in-wpf[^]
 
Share this answer
 
Comments
Arthur Dragon 16-Dec-22 5:53am    
Could I just do it through the two button clicks?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900