gpt4 book ai didi

wpf - 重新定义控件模板时,依赖属性从何而来?

转载 作者:行者123 更新时间:2023-12-04 06:27:22 27 4
gpt4 key购买 nike

假设您有 2 个 WPF 按钮。一种使用 TextBlock,而不是另一种。

<Button x:Name="Button1">
<TextBlock>inside textblock</TextBlock>
</Button>


<Button x:Name="Button2">
no textblock
</Button>

两个按钮都使用此模板将“前景”依赖属性设置为白色:
<ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">            
<Border Name="Border" TextElement.Foreground="White">
<ContentPresenter/>
</ControlTemplate>

带有 TextBlock 的按钮具有黑色文本。另一个工作正常。为什么?

最佳答案

这是一个值(value)继承问题,因为 H.B.指出。属性值继承一般遵循逻辑树。

在第一种情况下:

<Button x:Name="Button1">
<TextBlock>inside textblock</TextBlock>
</Button>

TextBlock 的逻辑父级是 Button,因此它将从 Button 继承它的值,依此类推逻辑树。所以在下面的代码中,TextBlock 将是红色的:
<Button x:Name="Button1" TextBlock.Foreground="Red">
<TextBlock>inside textblock</TextBlock>
</Button>

在第二种情况下:
<Button x:Name="Button2">
no textblock
</Button>

TextBlock 最终由 ContentPresenter 创建(请参阅 ILSpy/Reflector 中的 ContentPresenter.ChooseTemplate 方法)。在这种情况下,TextBlock 的逻辑父级是 ContentPresenter。所以它将从 ContentPresenter 继承它的值,依此类推逻辑树,到定义了白色前景的 Border。

这是简要记录 here .

关于wpf - 重新定义控件模板时,依赖属性从何而来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5881299/

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