3

如何将画布“停靠”在其父级中?

我有一个包含画布的 UserControl。

<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>

我在里面使用这个自定义画布的WidthHeight属性。并且需要该属性始终“绑定”到父容器。

4

3 回答 3

5

试试这个

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

身高也是一样

于 2010-10-27T10:09:21.720 回答
2

如果不设置WidthHeight属性,Canvas它将占用UserControl. 这是一个简单的例子:

[主窗口.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" />

如果您运行此应用程序,您会看到背景颜色为红色,这意味着Canvas占用了UserControl(及其父级Grid)提供的所有可用空间。您还可以调整窗口大小 -Canvas将随之而来。

于 2010-10-27T10:35:15.553 回答
0
<MyCanvas x:Name="myCanvas" 
     Width ="{Binding ElementName=myUserControl, Path=Width}" 
     Height="{Binding ElementName=myUserControl, Path=Height}">
</MyCanvas>
于 2020-12-05T00:35:47.733 回答