WPF获取Stackpanel儿童邻居

时间:2016-11-28 00:37:49

标签: c# wpf grid nearest-neighbor stackpanel

我有一个基于其他地方定义的2D数组动态添加按钮的堆栈面板。所以基本上它构建了一个按钮网格,但作为stackpanel的子项添加。我需要做的是根据列号和行号指定子按钮。这是Stackpanel。

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

这是一些有问题的代码。

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

现在,点击一个按钮,我想隐藏网格中的所有相邻按钮。这是我的点击事件:

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

我如何在ButtonClick中隐藏包含colrow值的邻居按钮?是否有某种getter或setter,而不是我可以将这些值提供给并编辑邻居的Visibility属性?

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

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

这会迭代您的孩子,如果它是Button的类型,它会检查rowcolumn是否在您的Source旁边并隐藏它。

相关问题