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