i have a big problem and i am searching for a long time but i dont find the answer so i ask here now. I know how get Column and Row of something what i clicked and can set UI Elements but i cant check if for example a playstone is on row 1 and column 1. How i get access for a specif cell, i want check if a specific cell is a button or empty. Thanks for everyone who tries to answer this question.
What i know: How to get rows:
Button btn = sender as Button;
var Spalte = Grid.GetColumn(btn);
var Zeile = Grid.GetRow(btn);
How to set a Element:
Grid.SetColumn(Spielstein, Spalte);
Grid.SetRow(Spielstein, Zeile);
What i dont know: Access the Cell of Row 1 and Column 1 and check if this is a Button
Good Night, As far as I know, it is not possible in wpf to access a specific cell in the Grid
. Use:
var Spalte = Grid.GetColumn(btn);
var Zeile = Grid.GetRow(btn);
There isn't a direct way of access the element by the column-row position of a Grid element, but you can write a utility method that do this, iterating over the children items of the Grid element and get the column and row position of that element like you did it before. I write an example of this utility method named GetElementInGridPosition:
The code in the 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;
}
}
and the 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.