tags:

views:

24

answers:

2

How can I "dock" a canvas in its parent?

I have a UserControl that contains a canvas inside.

<UserControl x:Class="MyUC"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d"              
         d:DesignHeight="300" d:DesignWidth="300">
    <MyCanvas x:Name="myCanvas" 
        Height="???" 
        Width="???{Binding RelativeSource={RelativeSource TemplatedParent}}" >
    </MyCanvas>
</UserControl>

I use Width and Height properties of this custom canvas inside. And need that that properties be always "bind" to the parent Container.

A: 

Try this

Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl, AncestorLevel=1}, Path=ActualWidth}"

Same goes for height

A: 

If you don't set the Width and Height properties in the Canvas it will occupy all the space available in the UserControl. Here's a simple example:

[MainWindow.xaml]

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Width="500" Height="500"
        x:Class="WpfApplication1.MainWindow">
    <Grid Background="Blue">
        <local:UserControl1 />
    </Grid>
</Window>

[UserControl1.xaml]

<UserControl x:Class="WpfApplication1.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Background="Green">
<Canvas Background="Red" />

If you run this app, you'll see that the background color is red, meaning that the Canvas takes all of the space made available by the UserControl (and its parent Grid). You can also resize the window - the Canvas will follow.

robertos
as I said, I use `Width` and `Height` properties, so I need to set it explicitly, if not they will be NaN, and I can't use ActualWidth/Height instead.
serhio
In that case the solution above works. Another option is to simply name your parent UserControl and use regular Element Binding (e.g. Width="{Binding ElementName=myUserControl, Path=ActualWidth}").
robertos