Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 343
ashish nirkhe Avatar asked Jun 25 '13 23:06

ashish nirkhe


1 Answers

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"/>
like image 100
Simon Belanger Avatar answered Nov 07 '22 03:11

Simon Belanger