我在一个DataTemplate
中有一个用户控件,TextBlock
的Style
不会改变FontSize
,但会改变Background
。
附上示例:
Create a WPF window.
Create a User control,
UserControl1
Inside the Window paste the below code:
<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}" /> <!--<m:UserControl1 />--> </StackPanel> </ContentControl> </Grid>
In the 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>
我们有两个文本块,拥有相同的背景颜色——蓝色,但是字体大小不同。
textBlockInResourse FontSize = 20
,从样式 TextBlockStyleFontAndBackgound
中获取。
textBlockInControl FontSize = 10
,继承值,为什么会发生这种情况呢?
我在用户控件中添加了一个句柄:
private void Button_Click(object sender, RoutedEventArgs e)
{
Style style = FindResource("TextBlockStyleFontAndBackgound") as Style;
textBlockInControl.Style = null;
textBlockInControl.Style = style;
}
现在字体被设置为样式TextBlockStyleFontAndBackgound
,大小为20
现在FontSize
是从TextBlockStyleFontAndBackgound
样式中获取的。
谢谢, barak