我有以下XAML代码(简化版):
<Window ...
<Window.Resources>
<Style TargetType="{x:Type TextBlock}" >
<Setter Property="FontSize" Value="28" />
<Setter Property="Margin" Value="3" />
<Setter Property="Foreground" Value="Green" />
</Style>
</Window.Resources>
<StackPanel>
<ListBox ItemsSource=...
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<TextBlock Text="{Binding Index}" />
<TextBlock Text="-" />
<TextBlock Text="{Binding Hours, StringFormat={}{0:00}}" />
<TextBlock Text=":" />
<TextBlock Text="{Binding Minutes, StringFormat={}{0:00}}" />
<TextBlock Text=":" />
<TextBlock Text="{Binding Seconds, StringFormat={}{0:00}}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
...
使用此代码,Window.Resources 中定义的样式未应用于 DataTemplate 内部的 TextBlock,但是在窗口的其他 TextBlock 上应用了该样式。
如果我将 Style 复制并在 DataTemplate 资源中设置如下:
<DataTemplate.Resources>
<Style TargetType="{x:Type TextBlock}" >
<Setter Property="FontSize" Value="28" />
<Setter Property="Margin" Value="3" />
<Setter Property="Foreground" Value="Green" />
</Style>
</DataTemplate.Resources>
然后它就可以工作了。你有什么想法为什么需要重复样式?
提前感谢。
DefaultStyleKey
еұһжҖ§пјҢиҖҢTextBlock
е·Із»Ҹе®һзҺ°дәҶе®ғгҖӮ - Eli ArbelDefaultStyleKey
并在您的Window
中编写隐式样式是不同的。基本上,当非System.Windows.Controls.Control
元素的样式被评估时,它不会超出该模板以检查其他元素资源,而是直接转到Application.Resources
,然后是DefaultStyleKey
。 - dkozl