2016-11-28 117 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