La respuesta anterior de EvAlex funcionará, pero solo si no desea establecer el número de columnas/filas mediante el enlace de datos.
public class GridEx : Grid
{
public int NumberOfRows
{
get { return RowDefinitions.Count; }
set
{
RowDefinitions.Clear();
for (int i = 0; i < value; i++)
RowDefinitions.Add(new RowDefinition());
}
}
public int NumberOfColumns
{
get { return ColumnDefinitions.Count; }
set
{
ColumnDefinitions.Clear();
for (int i = 0; i < value; i++)
ColumnDefinitions.Add(new ColumnDefinition());
}
}
}
Si desea establecer estos a través del enlace de datos (como yo), y luego con la solución anterior el compilador se quejará porque necesita DependencyProperties
para eso. Un DependencyProperty
pueden implementarse (usando C# de 6 nameof
operador) de la siguiente manera (una forma rápida de insertar está utilizando el propdp fragmento):
public int Columns
{
get { return (int) GetValue(ColumnsDependencyProperty); }
set { SetValue(ColumnsDependencyProperty, value); }
}
public static readonly DependencyProperty ColumnsDependencyProperty =
DependencyProperty.Register(nameof(Columns), typeof(int), typeof(GridEx), new PropertyMetadata(0));
Pero de esta manera no se puede ejecutar la lógica necesaria para añadir la necesaria número de RowDefinitions
. Para solucionar esto, defina DependencyPropertyDescriptor
para cada DependencyProperty
y agregue una llamada AddValueChanged
con la lógica necesaria en el constructor de su clase personalizada. El resultado por Propery es entonces (usando C# de 6 operador null-condicional ?.
):
public int Columns
{
get { return (int) GetValue(ColumnsDependencyProperty); }
set { SetValue(ColumnsDependencyProperty, value); }
}
public static readonly DependencyProperty ColumnsDependencyProperty =
DependencyProperty.Register(nameof(Columns), typeof(int), typeof(GridEx), new PropertyMetadata(0));
DependencyPropertyDescriptor ColumnsPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(ColumnsDependencyProperty, typeof(GridEx));
public GridEx()
{
ColumnsPropertyDescriptor?.AddValueChanged(this, delegate
{
ColumnDefinitions.Clear();
for (int i = 0; i < Columns; i++)
ColumnDefinitions.Add(new ColumnDefinition());
});
}
Cómo definido locales –