gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:33 24 4
gpt4 key购买 nike

我今天的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com