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
了點。一個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
。要解決這個問題,請爲每個DependencyProperty
定義一個DependencyPropertyDescriptor
,並在您的自定義類的構造函數中添加一個調用AddValueChanged
所需的邏輯。然後每個propery的結果是(使用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());
});
}
來源
2016-11-24 17:59:42
JvS
如何定義本地 –