WPF将RowDefinition.Height属性绑定到DataTemplate中Height = Auto的另一个RowDefinition

时间:2014-07-17 10:45:24

标签: c# wpf xaml

我想在WPF数据模板中的网格中创建3行。第一个设置为Height = Auto,第二个填充可用空间,第三个等于第一个。我尝试过绑定到elementname,但这似乎无法正常工作

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" x:Name="definition" />
        <RowDefinition Height="*" />
        <RowDefinition Height="{Binding ElementName=definition, Path=ActualHeight}" />
    </Grid.RowDefinitions>

    <TextBox Grid.Row="0" Height="100" />
</Grid>

在这个例子中,我希望第三行的高度也是100px。有什么建议吗?

2 个答案:

答案 0 :(得分:3)

RowDefinition.ActualHeight不是实际的依赖属性,这意味着您的绑定无法获得任何更新&#34;关于ActualHeight被更改。

您可以遵循以下模式:

<Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
    <RowDefinition Height="{Binding ElementName=FirstRow, Path=ActualHeight}" />

    <Grid Grid.Row="0" x:Name="FirstRow" />
    <Grid Grid.Row="1" x:Name="SecondRow" />
    <Grid Grid.Row="2" x:Name="ThirdRow" />
</Grid.RowDefinitions>

理论上这应该起作用的原因很简单:RowDefinition.ActualHeight == FirstRow.ActualHeight(默认情况下它应该填充可用空间)

或者,只需窃取RowDefinition,也可以创建自己的CustomRowDefinition,它可以实现依赖属性,称为ActualHeight,以及激活更新。

http://dotnetinside.com/in/type/PresentationFramework/RowDefinition/4.0.0.0

答案 1 :(得分:3)

试试这个:

<Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid Height="100" Background="Red" x:Name="definition"/>
    <Grid Background="Green" Grid.Row="1"/>
    <Grid Background="Blue" Grid.Row="2" Height="{Binding ElementName=definition, Path=ActualHeight}"/>
</Grid>