【问题标题】:Dock a Canvas in its parent将 Canvas 停靠在其父级中
【发布时间】:2010-10-27 09:52:24
【问题描述】:

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

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

<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 属性。并且需要这些属性始终“绑定”到父容器。

【问题讨论】:

  • 这样你的 UserControl 总是和上面的容器一样大吗?可以多贴一点 xaml 吗?
  • @user109134:UserControl 也应该停靠在它的父级 - 一个表单上。所以它的尺寸是可变的

标签: wpf canvas dock


【解决方案1】:

试试这个

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

身高也一样

【讨论】:

    【解决方案2】:

    如果您没有在Canvas 中设置WidthHeight 属性,它将占用UserControl 中的所有可用空间。这是一个简单的例子:

    [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" />
    

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

    【讨论】:

    • 正如我所说,我使用WidthHeight 属性,所以我需要明确设置它,否则它们将是NaN,我不能使用ActualWidth/Height 代替。
    • 在这种情况下,上述解决方案有效。另一种选择是简单地命名您的父 UserControl 并使用常规元素绑定(例如 Width="{Binding ElementName=myUserControl, Path=ActualWidth}")。
    • 如果画布在网格中,删除宽度和高度不会扩展画布...
    【解决方案3】:
    <MyCanvas x:Name="myCanvas" 
         Width ="{Binding ElementName=myUserControl, Path=Width}" 
         Height="{Binding ElementName=myUserControl, Path=Height}">
    </MyCanvas>
    

    【讨论】:

    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2013-11-24
    • 1970-01-01
    • 2012-10-07
    相关资源
    最近更新 更多