2010-10-27 35 views
2

如何「停靠」其父項中的畫布?將畫布停放在其父項中

我有一個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性能。並且需要該屬性始終「綁定」到父容器。

+0

這樣,您的UserControl始終與上面的容器大小相同?你可以粘貼更多的xaml嗎? – user109134 2010-10-27 09:59:25

+0

@ user109134:UserControl也應該停靠在其父 - 表單上。所以它的尺寸是可變的 – serhio 2010-10-27 10:03:49

回答

2

試試這個

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

也是一樣的高度

2

如果您沒有設置在CanvasWidthHeight性能會佔用所有的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將隨之改變。

+0

正如我所說的,我使用'Width'和'Height'屬性,所以我需要明確地設置它,如果它們不是NaN,我不能使用ActualWidth/Height。 – serhio 2010-10-27 11:12:10

+0

在這種情況下,上述解決方案的工作。另一種選擇是簡單地命名您的父級UserControl並使用常規元素綁定(例如,Width =「{Binding ElementName = myUserControl,Path = ActualWidth}」)。 – robertos 2010-10-27 19:09:16

+0

如果畫布位於網格中,移除寬度和高度不會展開畫布... – serhio 2012-03-06 13:31:58

相關問題