2016-11-28 103 views
1

我有一个基于其他地方定义的2D数组的动态添加按钮的堆叠面板。所以本质上它构建了一个按钮的网格,但添加为堆栈面板的子节点。我需要做的是,根据列和行号指定一个子按钮。这是Stackpanel。WPF获取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属性?

+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,将其隐藏。

+0

当我尝试利用它时,'Grid.Children'段下面有红线,错误信息为'非静态字段,方法或属性'Panel.Children''需要对象引用。我不是WPF的超级棒,你知道我是如何解决这个 – user3066571

+0

@ user3066571:更新了我的答案。现在它应该工作。在我的例子中,我之前使用了一个带有x:Name =“Grid”的'Grid'。现在使用父源代码对我来说工作正常。 – WPFGermany

+0

谢谢,那真的很好。 – user3066571