Grid.RowDefinitions
和Grid.ColumnDefinitions
不是依赖属性,因此不能通过样式来设置。
你可以在UserControl中创建一个依赖属性FirstRowHeight
,并将第一个RowDefinition
的Height
绑定到该属性。稍后可以在Style
中设置FirstRowHeight
属性。
<Grid.RowDefinitions>
<RowDefinition Height="{Binding FirstRowHeight,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"/>
<RowDefinition/>
</Grid.RowDefinitions>
该属性应该是这样的:
public static readonly DependencyProperty FirstRowHeightProperty =
DependencyProperty.Register(
"FirstRowHeight", typeof(GridLength), typeof(YourUserControl));
public GridLength FirstRowHeight
{
get { return (GridLength)GetValue(FirstRowHeightProperty); }
set { SetValue(FirstRowHeightProperty, value); }
}
编辑:为了支持你在问题结尾提到的简单场景,你也可以有一个
IsFirstRowFixed
依赖属性,具有一个属性更改回调函数,用于在代码中设置行高度。
<Grid.RowDefinitions>
<RowDefinition x:Name="row1" Height="*"/>
<RowDefinition x:Name="row2" Height="Auto"/>
</Grid.RowDefinitions>
该属性:
public static readonly DependencyProperty IsFirstRowFixedProperty =
DependencyProperty.Register(
"IsFirstRowFixed", typeof(bool), typeof(UserControl2),
new PropertyMetadata((o, e) => ((UserControl2)o).IsFirstRowFixedChanged()));
public bool IsFirstRowFixed
{
get { return (bool)GetValue(IsFirstRowFixedProperty); }
set { SetValue(IsFirstRowFixedProperty, value); }
}
private void IsFirstRowFixedChanged()
{
if (IsFirstRowFixed)
{
row1.Height = GridLength.Auto;
row2.Height = new GridLength(1, GridUnitType.Star);
}
else
{
row1.Height = new GridLength(1, GridUnitType.Star);
row2.Height = GridLength.Auto;
}
}