I have a user control in a DataTemplate , Style for TextBlock does not change FontSize , but changes Background .
Attached examples:
Create a WPF window.
Create a UserControl1 User Control
Inside the window, paste the code below:
<Window.Resources> <Style TargetType="{x:Type TextBlock}" x:Key="TextBlockStyleFontAndBackgound"> <Setter Property="FontSize" Value="20" /> <Setter Property="Background" Value="Blue" /> </Style> <DataTemplate x:Key="contentTemplate"> <StackPanel> <m:UserControl1 /> </StackPanel> </DataTemplate> </Window.Resources> <Grid> <ContentControl FontSize="10"> <StackPanel x:Name="stackPanel"> <Button Click="Button_Click" /> <ContentControl ContentTemplate="{StaticResource contentTemplate}" /> </StackPanel> </ContentControl> </Grid>
In user control, paste the following code:
<UserControl.Resources> <DataTemplate x:Key="contentTemplateInsideUserControl"> <TextBlock Name="textBlockInResourse" Text="textBlockInsideUserControlResource" Style="{DynamicResource TextBlockStyleFontAndBackgound}"/> </DataTemplate> </UserControl.Resources> <Grid> <StackPanel> <ContentControl ContentTemplate="{StaticResource contentTemplateInsideUserControl}" /> <Button Content="St" Click="Button_Click" /> <TextBlock Name="textBlockInControl" Text="textBlockInsideUserControl" Style="{DynamicResource TextBlockStyleFontAndBackgound}" /> </StackPanel> </Grid>
We have 2 text blocks with the same background color, blue, but with different font sizes.
textBlockInResourse FontSize = 20 , taken from the TextBlockStyleFontAndBackgound style
textBlockInControl FontSize = 10 , inherited value, why is this happening?
I added a handle to the user element:
private void Button_Click(object sender, RoutedEventArgs e) { Style style = FindResource("TextBlockStyleFontAndBackgound") as Style; textBlockInControl.Style = null; textBlockInControl.Style = style; }
And now the Font set to the TextBlockStyleFontAndBackgound style, and the size is 20
Why now FontSize is taken from the TextBlockStyleFontAndBackgound style.
Thanks Barak
barak source share