您可以扩展当前的 Grid 控件并添加一些自定义依赖属性(EG 列和行)并绑定到这些。这将允许您保持 MVVM 模式。
例如
public class MyGridControl : Grid
{
public static readonly DependencyProperty RowsProperty =
DependencyProperty.Register("Rows", typeof(int), typeof(MyGridControl), new PropertyMetadata(RowsChanged));
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register("Columns", typeof(int), typeof(MyGridControl), new PropertyMetadata(ColumnsChanged));
public static void RowsChanged(object sender, DependencyPropertyChangedEventArgs args)
{
((MyGridControl)sender).RowsChanged();
}
public static void ColumnsChanged(object sender, DependencyPropertyChangedEventArgs args)
{
((MyGridControl)sender).ColumnsChanged();
}
public int Rows
{
get { return (int)GetValue(RowsProperty); }
set { SetValue(RowsProperty, value); }
}
public int Columns
{
get { return (int)GetValue(ColumnsProperty); }
set { SetValue(ColumnsProperty, value); }
}
public void RowsChanged()
{
//Do stuff with this.Rows
//E.G. Set the Row Definitions and heights
}
public void ColumnsChanged()
{
//Do stuff with this.Columns
//E.G. Set the Column definitions and widths
}
}
如果您的 VM 具有“行”和“列”属性,则 XAML 将如下所示:
<local:MyGridControl
Rows="{Binding Rows}"
Columns="{Binding Columns}">
</local:MyGridControl>