2015-09-04 187 views
0

我的谷歌賦的值今天是低的,因爲我只是無法找到答案,這真的很重要的問題:綁定屬性parent屬性

我在XAML從UserControl繼承創建自己的自定義控制。在裏面我有一個Grid和一些TextBlock s。

現在,我希望使用我的控件的任何人都能夠在我的控制下設置屬性Background。然後我想使用Background值來設置我的Grid上的Background屬性。

這裏是我的XAML和我的最新嘗試:

​​

而且自定義控件:

<!-- Foo.xaml --> 
<UserControl Name="UC"> <!-- snipped all namespace-stuff --> 
    <Grid Background="{Binding Path=Background, ElementName=UC}"> 
    <TextBlock Text="My custom control"/> 
    </Grid> 
</Page> 
+0

莫非你還張貼截圖? – Onur

回答

1

這個怎麼樣(背景網格作爲練習留給讀者......):

<UserControl Name="UC"> 

    <TextBlock Foreground="{Binding ElementName=UC, Path=Foreground}"/> 

</UserControl> 

完整的例子:

<Window x:Class="UnrelatedTests.Case8.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:case8="clr-namespace:UnrelatedTests.Case8" 
     Title="Window1" Height="300" Width="300"> 
    <Grid> 
     <case8:UserControl1 Background="Blue" Foreground="Red"/> 
    </Grid> 
</Window> 



<UserControl x:Class="UnrelatedTests.Case8.UserControl1" 
      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" 

      Name="UC1" 
      > 
    <Grid> 
     <TextBlock Background="White" Foreground="{Binding ElementName=UC1, Path=Foreground}">Text</TextBlock> 
    </Grid> 
</UserControl> 

design and runtime view

+0

它可以在'UserControl'的設計器中工作,但是在使用'UserControl'的控件的設計器或運行時無法獲得顏色。 –

+0

你能從「通話方」發佈一些代碼嗎? – Onur

+0

添加了XAML。 '前景'似乎是被繼承的,所以它可以在不需要綁定的情況下工作。所以我從我的問題中刪除了這部分。儘管如此,「Grid」上的「背景」仍然存在問題。 –

0

使用的RelativeSource對TextBlock的使用屬性從父電網的結合。

例如

{Binding Path=Background, RelativeSource={RelativeSource AncestorType={x:Type Grid}}} 
+0

'在'RelativeSource'類型中未找到'AncestorType'屬性' –