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は次のように ( DependencyProperty
C# 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
。これを解決するには、DependencyPropertyDescriptor
for 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());
});
}