【发布时间】:2013-01-08 07:34:12
【问题描述】:
有效的东西
我需要对作为 StackPanel 子级的某种类型的控件进行样式设置。我正在使用:
<StackPanel>
<StackPanel.Resources>
<Style TargetType="{x:Type TextBlock}">...</Style>
</StackPanel.Resources>
<TextBlock ...>
...
</StackPanel>
这很好用!每个 TextBlock 都会查看其父级(StackPanel)的资源,以了解它应该如何设置样式。将 TextBlock 嵌套在 StackPanel 下多远都没关系...如果它在其直接父级中找不到样式,它将查看其父级的父级,依此类推,直到找到某些东西(在这种情况下,在 ) 中定义的样式。
不起作用的东西
我在 ContentControl 中嵌套了一个 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 找到定义的样式?
谢谢...
【问题讨论】:
标签: wpf xaml controltemplate nested