ashish nirkhe
ashish nirkhe

Reputation: 697

How to stretch Rectangle over Grid cell in XAML

I need to add a rectangle in second row of the grid. I need rectangle to have width same as the width of Grid.

But the problem is, width of grid is decided at runtime. If I try to access Width or ActualWidth at the back code, I get NaN or 0.0 respectively.

ColumnSpan and Stretch are not working either. Here is the code:

<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>

Upvotes: 7

Views: 16891

Answers (1)

Simon Belanger
Simon Belanger

Reputation: 14880

Have you tried:

<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}}}"/>

Or if you have the Grid's name:

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

Edit: I forgot. I haven't worked much with Rectangle per se, but this might work too:

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

Upvotes: 17

Related Questions