c# - 将属性绑定(bind)到父属性的值

标签 c# wpf xaml

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

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

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

这是我最近尝试的 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>

最佳答案

这个怎么样(网格的背景留给读者练习......):

<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

关于c# - 将属性绑定(bind)到父属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32393709/

相关文章:

wpf - 折叠除第一个组之外的所有组

c# - WPF richTextBox问题

c# - 如何在 Windows Phone 中将对象传递到后台项目?

C# 更改特定行的背景颜色

c# - 使用 XML-RPC 编写以 C#、Ruby 和 Java 编写的分布式应用程序

c# - 具有唯一连续值的线程安全方式

c# - 尝试将数据从 WPF 应用程序发送到任何 Web 浏览器上的网页

c# - RestSharp 发布一个 JSON 对象

c# - asp.net 与 c#

wpf - 如何让我的 ScrollViewer 滚动查看区域?