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
如何定义本地 –