2009-10-30 40 views
2

我想將UserControl中的元素的屬性綁定到Silverlight中UserControl本身上設置的屬性。我相信它應該很簡單,但我還沒有設法使用RelativeSource或ElementName綁定。在這個例子中,我想讓矩形爲綠色(或任何UserControl的背景屬性設置爲)。綁定到Silverlight中的父元素的屬性

<UserControl x:Class="MyUserControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="40" Height="40" Background="Green" x:Name="root"> 
    <Grid x:Name="LayoutRoot" Background="White"> 
     <Rectangle x:Name="indicatorRectangle" Fill="{Binding Path=Background, ElementName=root}" Margin="0,0,26,0" /> 
    </Grid> 
</UserControl> 

有人知道正確的綁定語法嗎?

回答

2

有趣的是,我貼在原來的問題的XAML正常工作在VS2010,所以我認爲這是一件已經被固定在最新的Silverlight

2

試試這個:

<UserControl ... Background="Green" x:Name="root">  
    <Grid x:Name="LayoutRoot" Background="White">   
    <Rectangle x:Name="indicatorRectangle" 
     Fill="{Binding Background, ElementName=root}" Width="10" Height="10" /> 
    </Grid> 
</UserControl> 

它並沒有爲我工作,直到我給了矩形的寬度和高度。

2

請記住,如果你使用這個代碼將打破用戶控制並使用x:Name=設置名稱(在Silverlight 4.0,Visual Studio 10中)。

0

這需要MyUserControl類型的第一個祖先並綁定到它。

xmlns:controls="namespace of your control" ... 

<Rectangle x:Name="indicatorRectangle" Fill="{Binding Path=Background 
RelativeSource={RelativeSource AncestorLevel=1,AncestorType=controls:MyUserControl}"/>