WPF:创建可在多个视图中使用的控件的最佳方式
WPF: Best way to create a control that can used in multiple views
我有 5 个页面都具有这种网格结构:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<!-- TOP CONTENT HERE -->
</Grid>
<Grid Grid.Row="1">
<!-- MIDDLE CONTENT HERE -->
</Grid>
<Grid Grid.Row="2">
<!-- BOTTOM CONTENT HERE -->
</Grid>
现在显然这只是针对这个问题进行了简化 - 但我想避免的是在每个视图中使用完全相同的所有样式等网格布局。
问题是,我如何以最简单的方式创建一个控件,View1、View2..ViewN 可以添加到它们的 xaml 并指定它们认为合适的 TOP、MIDDLE 和 BOTTOM 内容?
这个简单的派生网格将根据需要自动排列三个子元素:
public class AutoGrid : Grid
{
public AutoGrid()
{
RowDefinitions.Add(new RowDefinition { Height = new GridLength(0, GridUnitType.Auto) });
RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
RowDefinitions.Add(new RowDefinition { Height = new GridLength(0, GridUnitType.Auto) });
}
protected override Size MeasureOverride(Size constraint)
{
for (int i = 0; i < Children.Count; i++)
{
SetRow(Children[i], i);
}
return base.MeasureOverride(constraint);
}
}
我有 5 个页面都具有这种网格结构:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<!-- TOP CONTENT HERE -->
</Grid>
<Grid Grid.Row="1">
<!-- MIDDLE CONTENT HERE -->
</Grid>
<Grid Grid.Row="2">
<!-- BOTTOM CONTENT HERE -->
</Grid>
现在显然这只是针对这个问题进行了简化 - 但我想避免的是在每个视图中使用完全相同的所有样式等网格布局。
问题是,我如何以最简单的方式创建一个控件,View1、View2..ViewN 可以添加到它们的 xaml 并指定它们认为合适的 TOP、MIDDLE 和 BOTTOM 内容?
这个简单的派生网格将根据需要自动排列三个子元素:
public class AutoGrid : Grid
{
public AutoGrid()
{
RowDefinitions.Add(new RowDefinition { Height = new GridLength(0, GridUnitType.Auto) });
RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
RowDefinitions.Add(new RowDefinition { Height = new GridLength(0, GridUnitType.Auto) });
}
protected override Size MeasureOverride(Size constraint)
{
for (int i = 0; i < Children.Count; i++)
{
SetRow(Children[i], i);
}
return base.MeasureOverride(constraint);
}
}