我有一个大问题,我已经搜索了很长时间,但是我找不到答案,所以我现在在这里问。我知道如何获得我单击的东西的列和行,并且可以设置UI元素,但是我无法检查例如在第1行和第1列上是否有一块橡皮泥。我如何访问特定单元格,我想检查特定单元格是按钮还是空。感谢所有试图回答这个问题的人。
我知道的是:如何获取行:
Button btn = sender as Button;
var Spalte = Grid.GetColumn(btn);
var Zeile = Grid.GetRow(btn);
如何设置元素:
Grid.SetColumn(Spielstein, Spalte);
Grid.SetRow(Spielstein, Zeile);
我不知道:访问第1行和第1列的单元格,并检查这是否是一个按钮
晚安!据我所知,在wpf中无法访问Grid
中的特定单元格。使用:
var Spalte = Grid.GetColumn(btn);
var Zeile = Grid.GetRow(btn);
没有通过Grid元素的列行位置直接访问元素的方法,但是您可以编写一个执行此操作的实用方法,遍历Grid元素的子项并获取列和行该元素的位置就像您之前所做的那样。我编写了一个名为GetElementInGridPosition的实用程序方法的示例:
窗口中的代码:
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) {
var element = this.GetElementInGridPosition(1, 1);
if (element is Button)
MessageBox.Show($"The element in 1,1 is a button.");
element = this.GetElementInGridPosition(2, 1);
if (element is Button)
MessageBox.Show($"The element in 2,1 is a button.");
else
MessageBox.Show($"The element in 2,1 isn't a button, it's a {element.GetType().Name}.");
}
private UIElement GetElementInGridPosition(int column, int row) {
foreach (UIElement element in this.RootGrid.Children) {
if (Grid.GetColumn(element) == column && Grid.GetRow(element) == row)
return element;
}
return null;
}
}
和xaml:
<Grid Name="RootGrid">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Button Click="ButtonBase_OnClick">Button</Button>
<Button Grid.Row="1" Grid.Column="1">Button in column 1, row 1</Button>
<Label Grid.Row="1" Grid.Column="2">Label in column 2, row 1</Label>
</Grid>