機能するもの
StackPanel の子である特定のタイプのコントロールのスタイルを設定する必要があります。私は使用しています:
<StackPanel>
<StackPanel.Resources>
<Style TargetType="{x:Type TextBlock}">...</Style>
</StackPanel.Resources>
<TextBlock ...>
...
</StackPanel>
そして、これはうまくいきます!各 TextBlock は、その親 (StackPanel) のリソースを参照して、スタイルを設定する方法を見つけます。TextBlock を StackPanel の下にどれだけネストしてもかまいません...直接の親にスタイルが見つからない場合は、何かが見つかるまで親の親などを調べます (この場合はで定義されたスタイル)。
うまくいかないもの
Template を持つ ContentControl 内に TextBlock をネストしたときに問題が発生しました (以下のコードを参照)。ControlTemplate は、TextBlock が親、祖父母などからスタイルを取得する方法を混乱させているようです...
ControlTemplate を効果的に使用すると、適切なスタイル (StackPanel.Resources にあるもの) を見つける TextBlock の手段が完全に無効になるようです。ControlTemplate に遭遇すると、ツリーの上のリソースでそのスタイルを探すのをやめ、代わりにアプリケーション自体の MergedDictionaries のスタイルにデフォルト設定します。
<StackPanel Orientation="Vertical" Background="LightGray">
<StackPanel.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Green" />
</Style>
</StackPanel.Resources>
<TextBlock Text="plain and simple in stackpanel, green" />
<ContentControl>
<TextBlock Text="inside ContentControl, still green" />
</ContentControl>
<ContentControl>
<ContentControl.Template>
<ControlTemplate TargetType="{x:Type ContentControl}">
<StackPanel Orientation="Vertical">
<ContentPresenter />
<TextBlock Text="how come this one - placed in the template - is not green?" />
</StackPanel>
</ControlTemplate>
</ContentControl.Template>
<TextBlock Text="inside ContentControl with a template, this one is green as well" />
</ContentControl>
</StackPanel>
StackPanel.Resources の Style を ControlTemplate.Resources に複製する以外に、その ControlTemplate 内の TextBlock に定義されたスタイルを見つける方法はありますか?
ありがとう...