代码之家  ›  专栏  ›  技术社区  ›  serhio

在父级停靠画布

  •  2
  • serhio  · 技术社区  · 14 年前

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

    我有一个包含画布的用户控件。

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

    我用 Width Height 此自定义画布的属性。并且需要该属性始终“绑定”到父容器。

    2 回复  |  直到 11 年前
        1
  •  4
  •   brunnerh    13 年前

    试试这个

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

    高度也一样

        2
  •  2
  •   robertos    14 年前

    如果你不设置 Width Height 中的属性 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>
    

    [用户控件1.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" />
    

    如果您运行此应用程序,您将看到背景色为红色,这意味着 帆布 占用了 用户控件 (及其母公司 Grid )您还可以调整窗口的大小- 帆布 接下来。

    推荐文章