在资源中按样式指定Grid列和行定义

Rys*_*gan 3 wpf xaml

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

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
</Grid>
Run Code Online (Sandbox Code Playgroud)

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

<Window.Resources>
    <Style TargetType="Grid">
        <Setter Property="RowDefinitions">
            <Value>
                <RowDefinition Height="*"/>
                <RowDefinition/>
            </Value>
        </Setter>
    </Style>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

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

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

Cle*_*ens 8

Grid.RowDefinitions并且Grid.ColumnDefinitions不是依赖属性,因此不能由Style设置.

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

<Grid.RowDefinitions>
    <RowDefinition Height="{Binding FirstRowHeight,
        RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"/>
    <RowDefinition/>
</Grid.RowDefinitions>
Run Code Online (Sandbox Code Playgroud)

该属性将如下所示:

public static readonly DependencyProperty FirstRowHeightProperty =
    DependencyProperty.Register(
        "FirstRowHeight", typeof(GridLength), typeof(YourUserControl));

public GridLength FirstRowHeight
{
    get { return (GridLength)GetValue(FirstRowHeightProperty); }
    set { SetValue(FirstRowHeightProperty, value); }
}
Run Code Online (Sandbox Code Playgroud)

编辑:为了支持您在问题结尾处描述的简单场景,您可能还有一个IsFirstRowFixed依赖属性,其属性已更改回调,用于设置代码中的行高:

<Grid.RowDefinitions>
    <RowDefinition x:Name="row1" Height="*"/>
    <RowDefinition x:Name="row2" Height="Auto"/>
</Grid.RowDefinitions>
Run Code Online (Sandbox Code Playgroud)

财产:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)