我正在尝试做一个 ControlTemplate 为一个 GroupBox 这样的话 TextBlockHeader 它的 Background 应该设置为黄色。

问题是,尽管我为 TextBlockContentPresenter 为了 Header, ,除了那些外,没有应用 TextBlock由WPF自动化的s。

这是代码:

<Window
  x:Class="TestHeaderTemplate.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1"
  SizeToContent="WidthAndHeight">
  <Window.Resources>    
    <Style
      TargetType="{x:Type GroupBox}">
      <Setter
        Property="Template">
        <Setter.Value>
          <ControlTemplate
            TargetType="{x:Type GroupBox}">            
            <Border
              Margin="{TemplateBinding Margin}"
              BorderBrush="Black"
              BorderThickness="1">
              <StackPanel>
                <Border
                  Margin="0,0,0,5"
                  BorderThickness="5"
                  BorderBrush="LightBlue"
                  >
                  <ContentPresenter
                    ContentSource="Header">
                    <ContentPresenter.Resources>
                      <Style
                        TargetType="{x:Type TextBlock}">
                        <Setter
                          Property="Background"
                          Value="Yellow" />
                      </Style>
                    </ContentPresenter.Resources>
                  </ContentPresenter>
                </Border>
                <ContentPresenter
                  ContentSource="Content" />
              </StackPanel>
            </Border>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </Window.Resources>
  <StackPanel>
    <TextBox
      Text="All TextBoxes in a GroupBox's Header should be yellow, whether declared or autogenerated." />
    <GroupBox
      x:Name="firstGroupBox"
      Margin="5"
      Header="I am a TextBlock autogenerated by WPF. Since I'm in the Header, I should be yellow.">
        <TextBlock
          Text="I'm a TextBlock declared in the content of the GroupBox. I should NOT be yellow." />      
    </GroupBox>
    <GroupBox
      x:Name="secondGroupbox"
      Margin="5"
      >
      <HeaderedContentControl.Header>      
          <TextBlock
            x:Name="notStyledTextBlock"
            Text="I'm a TextBlock declared in the header. I should be yellow since I'm in the header."
            VerticalAlignment="Center" />          
      </HeaderedContentControl.Header>
      <TextBlock
        Text="I'm declared in the content so I should not be yellow." />
    </GroupBox>
  </StackPanel>
</Window>

您可以看到是否尝试过 TextBlock 命名 notStyledTextBlock 在第二 GroupBox 不是黄色,这意味着在资源中定义的样式 ContentPresenter 在里面 ControlTemplate 不应用。

令人惊讶的是,由WPF自动化为第一个标题文本的容器 GroupBox 具有黄色的背景。

我该怎么做才能使我的风格适用于 notStyledTextBlock TextBlock?

有帮助吗?

解决方案

我在GroupBox和ContentPresenter方面也有问题。我已经发布了一个问题,因为没有给我答案,所以我对自己进行了一些调查。看着 答案,也许是同一问题(附加信息:我没有发布我的真实问题代码,而是一个简化的示例,可以用来复制)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top