开发者

Dock a Canvas in its parent

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:Desig开发者_如何学编程nWidth="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.


Try this

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

Same goes for height


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.


<MyCanvas x:Name="myCanvas" 
     Width ="{Binding ElementName=myUserControl, Path=Width}" 
     Height="{Binding ElementName=myUserControl, Path=Height}">
</MyCanvas>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜