The above EvAlex answer will work, but only if you don't want to set the number of columns / rows using data binding.
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()); } } }
If you want to install them using data binding (like me), then using the above solution, the compiler will complain, because it requires DependencyProperties
. A DependencyProperty
can be implemented (using the C # 6 nameof
) as follows (a quick way to insert it using the propdp fragment):
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));
But in this way, you cannot follow the necessary logic to add the required number of RowDefinitions
. To solve this problem, define a DependencyPropertyDescriptor
for each DependencyProperty
and add the AddValueChanged
call with the necessary logic to it in your own class constructor. Then the result on the property (using the null conditional operator C # 6 ?.
):
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()); }); }
source share