c# - 同一用户控件的不同WPF网格行大小规格取决于情况
问题描述
我已经完成了可重用的用户控件,在我的项目中使用了几次。
通常主网格的第二行需要比第一行大 7 倍,但在特定情况下,它只需要大 5 倍。
<Grid x:Name="mainGrid">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="7*"/>
</Grid.RowDefinitions>
...
</Grid>
我试图通过 XAML 设置它:
<helperControls:AttachmentsGridControl x:Name="projectAttachmentsControl" ... HeightOfSecondRow="5" />
在 .cs 部分:
public int HeightOfSecondRow { get; set; }
public AttachmentsGridControl()
{
InitializeComponent();
if(HeightOfSecondRow > 0)
this.mainGrid.RowDefinitions[1].Height = new GridLength(HeightOfSecondRow, GridUnitType.Star);
}
但是在调用控件的构造函数时不会传递值。该值需要在调用构造函数时传递,因此我可以指定第二行的高度需要多少并正确渲染。
解决方案
不要覆盖HeightOfSecondRow
构造函数中的 ,而是将其设置为类型的依赖属性,GridLength
默认值为7*
. 强制值回调将确保在 XAML 中设置或与绑定绑定的值为正值,否则将替换为默认值。
public partial class AttachmentsGridControl : UserControl
{
public static readonly DependencyProperty HeightOfSecondRowProperty = DependencyProperty.Register(
nameof(HeightOfSecondRow), typeof(GridLength), typeof(AttachmentsGridControl),
new PropertyMetadata(new GridLength(7, GridUnitType.Star), null, OnCoerceValue));
public GridLength HeightOfSecondRow
{
get => (GridLength)GetValue(HeightOfSecondRowProperty);
set => SetValue(HeightOfSecondRowProperty, value);
}
public AttachmentsGridControl()
{
InitializeComponent();
}
private static object OnCoerceValue(DependencyObject d, object value)
{
var gridLength = (GridLength)value;
return gridLength.Value > 0.0 ? gridLength : HeightOfSecondRowProperty.GetMetadata(d).DefaultValue;
}
}
调整 的绑定Height
以使用HeightOfSecondRow
您的AttachmentsGridControl
.
<Grid x:Name="mainGrid">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="{Binding HeightOfSecondRow, RelativeSource={RelativeSource AncestorType={x:Type local:AttachmentsGridControl}}}"/>
</Grid.RowDefinitions>
<!-- ...your content. -->
</Grid>
然后你可以HeightOfSecondRow
像以前一样设置。如果不设置,将使用默认值。
<local:AttachmentsGridControl x:Name="projectAttachmentsControl" HeightOfSecondRow="20*"/>
推荐阅读
- go - 如何修复未在函数中执行的日志函数?
- mysql - 创建触发器以在插入后为列分配值
- c# - 使用 EPPlus.Core 生成导出 excel 表
- r - 将多级 json/list 转换为 data.frame 或 data.table
- python - 多个类别的 Python 独立线性回归
- javascript - 如何正确创建和渲染功能组件?
- python - 将 Python 2 转换为 Python 3(使用 Python 2 样式执行)
- pandas - 熊猫绘制多个数据框,一个数据框产生一条扁平线
- sql-server - 在高可用性中与侦听器服务器连接时出现问题
- json - 如何将分层 JPA 实体正确映射到 dto 模型(通过 rest 保存和更新)