public static class GridExtensor
{
//This methods requires an element currently added to a grid.
public static void SetRow(UIElement element, object rowTag)
{
var prt = VisualTreeHelper.GetParent(element);
if (prt != null && prt is Grid grid)
SetRow(element, grid, rowTag);
}
public static void SetColumn(UIElement element, object columnTag)
{
var prt = VisualTreeHelper.GetParent(element);
if (prt != null && prt is Grid grid)
SetColumn(element, grid, columnTag);
}
public static void SetRow(UIElement element, Grid grid, object rowTag)
{
var idx = grid.RowDefinitions.FirstIndexWhere(row => row.Tag.Equals(rowTag));
Grid.SetRow(element, idx != -1 ? idx : 0);
}
public static void SetColumn(UIElement element, Grid grid, object columnTag)
{
var idx = grid.ColumnDefinitions.FirstIndexWhere(column => column.Tag.Equals(columnTag));
Grid.SetColumn(element, idx != -1 ? idx : 0);
}
public static void SetRowAndAdd(UIElement element, Grid grid, object rowTag)
{
SetRow(element, grid, rowTag)
if(!grid.Children.Contains(element))
grid.Children.Add(element);
}
public static void SetColumnAndAdd(UIElement element, Grid grid, object columnTag)
{
SetColumn(element, grid, columnTag);
if(!grid.Children.Contains(element))
grid.Children.Add(element);
}
public static int FirstIndexWhere<TSource>(this IList<TSource> source, Func<TSource, bool> predicate)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
if (predicate is null)
return 0;
int i = 0;
foreach (var element in source)
{
if (predicate(element))
{
return i;
}
i++;
}
return -1;
}
}
использование:
RowDefinition newRow = new RowDefinition();
newRow.Tag = "This is the row I want to find";
TextBlock newBlock = new TextBlock();
//options
currentGrid.RowDefinitions.Add(newRow); // important!!
currentGrid.Children.Add(newBlock); //important!!!!
GridExtensor.SetRow(newBlock, "This is the row I want to find");
//or
GridExtensor.SetRowAndAdd(newBlock, currentGrid, "This is the row I want to find");
//or
currentGrid.RowDefinitions.Add(newRow); // important!!
GridExtensor.SetRow(newBlock, currentGrid, "This is the row I want to find");
currentGrid.Children.Add(newBlock);