如何在XAML中将矩形拉伸到网格单元格上方

7
我需要在网格的第二行添加一个矩形。 我需要矩形的宽度与网格的宽度相同。
但是问题在于,网格的宽度在运行时确定。如果我试图在后台代码中访问 Width 或 ActualWidth,我会得到 NaN 或 0.0。
ColumnSpan 和 Stretch 也不起作用。 以下是代码:
<Grid x:Name="downloadPdfGrid">
    <Grid.RowDefinitions>
        <RowDefinition Height="20"/>
        <RowDefinition Height ="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button x:Name="btn" Content="{Binding Button}" Visibility="Collapsed" Click="OnButtonClick" Grid.Row="0"/>
    <Rectangle x:Name="underlineRect" Stretch="UniformToFill" Height="2" Fill="White" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1"/>
</Grid>
1个回答

17

你试过了吗:

<Rectangle x:Name="underlineRect" Stretch="UniformToFill" Height="2" Fill="White"
           Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1"
           Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}}"/>

或者如果您知道该网格的名称:

<Rectangle x:Name="underlineRect" Stretch="UniformToFill" Height="2" Fill="White"
           Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1"
           Width="{Binding ActualWidth, ElementName=downloadPdfGrid}"/>

编辑:我忘了。我本身没有和Rectangle一起工作过很多,但是这也可能有效:

<Rectangle x:Name="underlineRect" Stretch="UniformToFill" Height="2" Fill="White"
           Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1"
           HorizontalAlignment="Stretch"/>

1
除了网格之外,您还有其他未显示的内容。我刚刚启动了一个空的WPF应用程序,只在窗口中放置了您的网格,并测试了您的原始代码以及提出的所有三个更改建议,它们都可以正常工作(包括您自己的)。 - Simon Belanger
1
你是正确的。问题是由于父元素引起的。 谢谢Simon。现在它完美地工作了。 - ashish nirkhe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接