[英]WPF Access of Cell in a Grid
我有一个大问题,我正在寻找很长时间,但我没有找到答案,所以我现在在这里问。 我知道如何获取我单击的内容的列和行,并且可以设置 UI 元素,但我无法检查例如 playstone 是否在第 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 中的特定单元Grid
。 利用:
var Spalte = Grid.GetColumn(btn);
var Zeile = Grid.GetRow(btn);
没有直接的方法通过 Grid 元素的列行 position 访问元素,但是您可以编写一个实用方法来执行此操作,遍历 Grid 元素的子项并获取列和行 position像你以前那样做的那个元素。 我编写了一个名为 GetElementInGridPosition 的实用方法示例:
window中的代码:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.