3

有一个带有以下网格的 UserControl:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
</Grid>

现在我有一个窗口,我想写这样的东西:

<Window.Resources>
    <Style TargetType="Grid">
        <Setter Property="RowDefinitions">
            <Value>
                <RowDefinition Height="*"/>
                <RowDefinition/>
            </Value>
        </Setter>
    </Style>
</Window.Resources>

未编译的关键部分是当我想将高度从 Auto 更改为 *. 如何以合法的方式做到这一点?

一般来说,我必须案例。1)第一行应该拉伸,第二行应该固定。2) 反之亦然。也许与 Grid 不同的面板可能更相关?

4

2 回答 2

8

Grid.RowDefinitions并且Grid.ColumnDefinitions没有依赖属性,因此不能由样式设置。

您可能会FirstRowHeight在您的 UserControl 中创建一个依赖属性,并将Height第一个属性绑定RowDefinition到该属性。稍后您可以将FirstRowHeight属性设置在Style.

<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;
    }
}
于 2013-07-29T11:23:05.153 回答
0

XAML 代码:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="auto"/>
    </Grid.RowDefinitions>
<Grid Grid.Row="1" Style="{StaticResource HeaderHeight}"</>
<Grid Grid.Row="1" Style="{StaticResource FooterHeight}"</>
</>

资源字典中的样式

<Style TargetType="Frame" x:Name="HeaderHeight">
    <Setter Property="Height" Value="700"></Setter>
</Style>
<Style TargetType="Grid" x:Name="FooterHeight">
    <Setter Property="Height" Value="70"></Setter>
</Style>
于 2015-05-16T10:43:40.867 回答