Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAML How to get Canvas's Child to fill the entire Canvas?

if I have this XAML:

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
<StackPanel Orientation="Horizontal">
    <Grid Background="Gray" Margin="5"
        Height="200" Width="200">
        <Rectangle Fill="Blue" />
    </Grid>
    <Canvas Background="Gray" Margin="5"
        Height="200" Width="200">
        <Rectangle Fill="Blue" />
    </Canvas>
    <StackPanel Background="Gray" Margin="5"
        Height="200" Width="200">
        <Rectangle Fill="Blue" />
    </StackPanel>
</StackPanel>

Only the Grid is filled by the blue rectangle, But I would like the Canvas to operate the same way and be filled with the blue rectangle?

I am up for making a custom canvas, but not sure how to go about it.

Any suggestions?

like image 513
John Avatar asked Dec 06 '22 09:12

John


1 Answers

You could try something like this:

<Canvas x:Name="myCanvas" Background="Gray" Margin="5"
    Height="200" Width="200">
    <Rectangle Fill="Blue"
               Height="{Binding ElementName=myCanvas, Path=ActualHeight}"
               Width="{Binding ElementName=myCanvas, Path=ActualWidth}" />
</Canvas>

This will tell the rectangle to take it's dimensions from the actual dimensions of the named element.

The reason only the Grid is filled is because it's the only one that tells it's children what size to be. The StackPanel takes it's size from the combined size of all it's children and the Canvas is the size you tell it to be but doesn't resize any child elements.

like image 98
ChrisF Avatar answered Jan 17 '23 16:01

ChrisF