EvAlex による上記の回答は機能しますが、データ バインディングを使用して列/行の数を設定したくない場合に限ります。
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());
}
}
}
データバインディングを介してこれらを設定したい場合(私のように)、上記のソリューションでは、コンパイラーはそれが必要なDependencyPropertiesため文句を言います。Aは次のように ( DependencyPropertyC# 6 のnameof演算子を使用して) 実装できます (挿入する簡単な方法は、スニペット propdp を使用することです)。
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));
しかし、この方法では、必要な数の を追加するために必要なロジックを実行できませんRowDefinitions。これを解決するには、DependencyPropertyDescriptorfor eachを定義し、必要なロジックを含む呼び出しをカスタム クラスのコンストラクターにDependencyProperty追加します。AddValueChangedプロパティごとの結果は次のようになります (C# 6 の null 条件演算子を使用?.):
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());
});
}