XAML How do I get the Canvas 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 with a blue rectangle. But I would like the Canvas to work the same and fill with a blue rectangle?

I am about to create my own canvas, but I don’t know how.

Any suggestions?

+3


source to share


2 answers


You can 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 dimensions from the actual dimensions of the named item.

The reason only the grid is filled is because it is the only one that tells it what size it will be. The StackPanel takes its size from the combined size of all of its children, and Canvas is the size you're talking about, but not resizing all of its children.

+8


source


Since Canvas is not subject to HorizontalAlignment and VerticalAlignment , you need to explicitly specify the size of the nested element.

One parameter is element binding:

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

      



which is a bit fragile as it relies on the parent name (here myCanvas

). In WPF, you can get this with RelativeSource FindAncestor, but not in Silverlight or Windows 8.

You can find a number of workarounds / extensions to fill the FindAncestor gap - like this one - so it might be a more reusable option?

You might also be able to do something in the converter by traversing the visual tree to capture the dimensions of the canvas.

+2


source







All Articles