다른 곳에 정의 된 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
에서 col
및 row
값으로 이웃 버튼을 숨길 것인가? 그 값을 먹일 수 있고 이웃의 Visibility
속성을 편집 할 수있는 것보다 일종의 getter 나 setter가 있습니까? row
및 column
이 Source
옆 경우,
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
의 유형 인 경우는 확인하고 그것을 숨길 수 :
몇 가지 게임을 만들고 있습니까? 예, 맞춤 패널을 대신 사용해보십시오. 필요한 경우 샘플을 찾을 수 있습니다. –