DataTemplate中的UserControl未应用字体样式

4

我在一个DataTemplate中有一个用户控件,TextBlockStyle不会改变FontSize,但会改变Background

附上示例:

  1. Create a WPF window.

  2. Create a User control, UserControl1

  3. 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>
    
  4. 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

1个回答

1

这是一个非常奇怪的问题。我不确定为什么在不在中时FontSize没有受到影响...查看MSDN上的两个属性描述和备注,它们之间唯一的区别是TextBlock.FontSize也是一个AttachedProperty,但我无法看出它会影响什么。

如果您还感兴趣,我可以提供解决方案。尝试在您的App.xaml文件中声明您的Style

<Application.Resources>
    <Style TargetType="{x:Type TextBlock}" x:Key="TextBlockStyleFontAndBackgound">
        <Setter Property="FontSize" Value="20" />
        <Setter Property="Background" Value="Blue" />
    </Style>
</Application.Resources>

然后在您的UserControl中使用StaticResource声明您的TextBlock,如下所示:

<TextBlock Text="text" Style="{StaticResource TextBlockStyleFontAndBackgound}" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接