我想爲GroupBox
製作ControlTemplate
,這樣如果在Header
中聲明瞭TextBlock
,則應將其Background
設置爲黃色。WPF GroupBox ControlTemplate:如何僅將樣式應用於標題中的元素?
的問題是,雖然我在ContentPresenter
爲Header
定義TextBlock
秒的風格,它不是應用除了那些TextBlock
S的由WPF自動生成。
下面是代碼:
<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
?
將樣式中的邊框背景設置爲黃色將在您的示例中修復它,但也會爲標頭中使用的非文本塊添加黃色背景。我贊成HCL的回答,因爲我相信他給出的解釋,這是設計。 – 2010-09-09 13:24:11