将属性绑定到父属性的值

时间:2015-09-04 08:39:56

标签: c# wpf xaml

今天我的Google-Fu很低,因为我找不到这个真正微不足道的问题的答案:

我在XAML中创建自己的自定义控件,它继承自UserControl。在其中我有一个Grid和一些TextBlock s。

现在,我希望使用我的控件的任何人能够在我的控件上设置属性Background。然后我想使用Background值来设置Background上的Grid属性。

这是我最近尝试的XAML:

<!-- MainPage.xaml -->
<Page> <!-- snipped all namespace-stuff -->
  <local:Foo Background="Red" Foreground="White"/>
</Page>

自定义控件:

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

2 个答案:

答案 0 :(得分:1)

在TextBlock的绑定上使用RelativeSource以使用父网格中的属性。

e.g。

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

答案 1 :(得分: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

相关问题