If TargetType is set as ListBox, it work. But I want to set TargetType as TextBlock inside the ListBox. I know I can use x:Key ,but why it doesn't work without given x:Key ??
<Window x:Class="WpfApp6.DataTemplatesLab"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp6"
mc:Ignorable="d"
Title="DataTemplatesLab" Height="450" Width="800">
<Window.Resources>
<SolidColorBrush x:Key="DataColor" Color="Firebrick"/>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="28"/>
<Setter Property="Background" Value="Cyan"/>
</Style>
</Window.Resources>
<ListBox x:Name="ListPersonals" Width="600">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}" Grid.Row="0" />
<TextBlock Text="{Binding Gender}" Grid.Row="1" />
<TextBlock Text="{Binding Email}" Grid.Row="2" />
<TextBlock Text="{Binding Title}" Grid.Row="3" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
CodePudding user response:
You would need to either use the key or define the style at the DataTemplate level.
<ListBox x:Name="ListPersonals" Width="600" ItemsSource="{Binding DemoCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<DataTemplate.Resources>
<Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}" />
</DataTemplate.Resources>
This is because the DataTemplates work as an encapsulation boundary. This means any look-up for styles based on TargetType stops at the DataTemplate.
Please note the styles defined in App.xaml is an exception to this rule. If you were to define the Style Resource in app.xaml, the style would applied to the inner controls even without redefining them within the DataTemplate