Search code examples
c#wpfgridnearest-neighborstackpanel

WPF Get Stackpanel children neighbors


I have a stackpanel that I have dynamically added buttons to, based on a 2D array defined elsewhere. So essentially it builds a grid of buttons, but added as children of the stackpanel. What I need to be able to do, is specify a child button based on column and row number. Here's the Stackpanel.

<StackPanel Name="myArea"  HorizontalAlignment="Center" VerticalAlignment="Center"/>

And here's some of the code in question.

Grid values = new Grid();
values.Width = 320;
values.Height = 240;
values.HorizontalAlignment = HorizontalAlignment.Center;
values.VerticalAlignment = VerticalAlignment.Center;

int x = valueBoard.GetLength(0);
int y = valueBoard.GetLength(1);

for (int i = 0; i < x; i++)
{
    ColumnDefinition col = new ColumnDefinition();
    values.ColumnDefinitions.Add(col);
}
for (int j = 0; j < y; j++)
{
    RowDefinition row = new RowDefinition();
    values.RowDefinitions.Add(row);
}
for (int i = 0; i < x; i++) for (int j = 0; j < y; j++)
{
    Button button = new Button();
    button.Content = "";
    button.Click += ButtonClick;  
    button.MouseRightButtonUp += RightClick;
    Grid.SetColumn(button, i);
    Grid.SetRow(button, j);
    values.Children.Add(button);
}
myArea.Children.Add(values);  

So now, on click of a button, I want to hide all adjacent buttons in the grid. Here's my click event:

private void ButtonClick(object sender, RoutedEventArgs e)
{
    int col = Grid.GetColumn((Button)sender);
    int row = Grid.GetRow((Button)sender);
    Button source = e.Source as Button;
    source.Visibility = Visibility.Hidden;
}

How would I, in ButtonClick, hide the neighbor buttons with the col and row values? Is there some sort of getter or setter than I can feed those values into and edit the neighbor's Visibility property?


Solution

  • try the following:

    private void ButtonClick(object sender, RoutedEventArgs e)
    {
        int col = Grid.GetColumn((Button)sender);
        int row = Grid.GetRow((Button)sender);
        Button source = e.Source as Button;
        source.Visibility = Visibility.Hidden;
        Grid pGrid = source.Parent as Grid;
        if (pGrid == null) throw new Exception("Can't find parent grid.");
    
        for (int i = 0; i < pGrid.Children.Count; i++) {
            Button childButton = pGrid.Children[i] as Button;
            if(childButton == null) continue;
    
            int childCol = Grid.GetColumn(childButton);
            int childRow= Grid.GetRow(childButton);
    
            if(Math.Abs(childCol - col) < 2 && Math.Abs(childRow - row) < 2) childButton.Visibility = Visibility.Hidden;
        }
    }
    

    this iterates through your children and if it is type of Button it will check, if the row and column is next to your Source and will hide it.