DataGrid中TextBlock隐式样式仅在App.xaml声明时生效的疑问
DataGrid中TextBlock隐式样式的生效问题
我无法理解为何DataGrid中的TextBlock隐式样式只有在App.xaml中定义时才会生效,这似乎违背了“可视化树(VisualTree)中越靠近使用者的样式越优先应用”的规则。无论在DataGrid.Resources、Window.Resources中定义,还是同时定义,都没有效果。为便于对比,我添加了Label的样式,其效果符合预期。
测试代码(MainWindow.xaml)
<Window x:Class="DasDataGrid.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="DataGrid Implicit Styles" Width="300" SizeToContent="Height" FontSize="14" WindowStartupLocation="CenterScreen"> <Window.Resources> <x:Array x:Key="champions" Type="{x:Type sys:String}"> <sys:String>Jim Clark</sys:String> <sys:String>Jochen Rindt</sys:String> </x:Array> <Style TargetType="TextBlock"> <Setter Property="Foreground" Value="Red"/> </Style> </Window.Resources> <DataGrid ItemsSource="{StaticResource champions}" AutoGenerateColumns="False" MinRowHeight="35"> <DataGrid.Resources> <ResourceDictionary> <Style TargetType="TextBlock"> <Setter Property="Foreground" Value="Red"/> </Style> <Style TargetType="Label"> <Setter Property="Foreground" Value="Red"/> </Style> </ResourceDictionary> </DataGrid.Resources> <DataGrid.Columns> <DataGridTemplateColumn Header="Champion (TextBlock)" Width="*"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="Champion (Label)" Width="*"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Label Content="{Binding}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid>
运行效果
运行上述代码后,**Champion (TextBlock)**列的文字保持默认颜色,**Champion (Label)**列的文字变为红色(符合预期)。
修改后的代码(App.xaml)
<Application x:Class="DasDataGrid.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> <Application.Resources> <Style TargetType="TextBlock"> <Setter Property="Foreground" Value="Red"/> </Style> </Application.Resources>
修改后的运行效果
将TextBlock的隐式样式移到App.xaml中后,**Champion (TextBlock)列和Champion (Label)**列的文字均变为红色,样式生效。
内容的提问来源于stack exchange,提问作者Felix Liebrecht
相关产品推荐
相关产品推荐

