有用的东西
我需要对作为 StackPanel 的子项的某种类型的控件进行样式设置。我正在使用:
<StackPanel>
<StackPanel.Resources>
<Style TargetType="{x:Type TextBlock}">...</Style>
</StackPanel.Resources>
<TextBlock ...>
...
</StackPanel>
这很好用!每个 TextBlock 都会查看其父级(StackPanel)的资源,以了解应如何设置样式。将 TextBlock 嵌套在 StackPanel 下多远都没关系......如果它在其直接父级中找不到样式,它将查看其父级的父级,依此类推,直到找到某些东西(在这种情况下, 中定义的样式)。
不起作用的东西
当我将 TextBlock 嵌套在具有模板的 ContentControl 中时遇到了问题(请参见下面的代码)。ControlTemplate 似乎破坏了 TextBlock 从其父母、祖父母、...
ControlTemplate 的使用似乎有效地消除了 TextBlock 寻找其正确样式的方法(StackPanel.Resources 中的那个)。当它遇到 ControlTemplate 时,它会停止在树上的资源中查找其样式,而是默认为 Application 本身的 MergedDictionaries 中的样式。
<StackPanel Orientation="Vertical" Background="LightGray">
<StackPanel.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Green" />
</Style>
</StackPanel.Resources>
<TextBlock Text="plain and simple in stackpanel, green" />
<ContentControl>
<TextBlock Text="inside ContentControl, still green" />
</ContentControl>
<ContentControl>
<ContentControl.Template>
<ControlTemplate TargetType="{x:Type ContentControl}">
<StackPanel Orientation="Vertical">
<ContentPresenter />
<TextBlock Text="how come this one - placed in the template - is not green?" />
</StackPanel>
</ControlTemplate>
</ContentControl.Template>
<TextBlock Text="inside ContentControl with a template, this one is green as well" />
</ContentControl>
</StackPanel>
有没有办法——除了将 StackPanel.Resources 中的 Style 复制到 ControlTemplate.Resources 之外——让 ControlTemplate 中的 TextBlock 找到定义的样式?
谢谢...