「Androidは電気羊の夢を見るか」を読みたい管理者のブログ

仕事などでの色々な発見を記事にしてます。不定期更新。

ControlTemplateとStyleは明示的に使い分ける必要があるんだってばよ


Style.TriggersとControlTemplate.Triggersの違い - プログラマーな日々


■StyleとItemTemplateの違いはなあに?
①書く場所が違います。
Styleはソースコードの上に書いてターゲットを指定するのに対して
TemplateはButtonなどの属性として書く。

②優先順位が違います。
たぶんTemplateの方が優先度が高いんじゃないかな。
と考えるとリンク先

Buttonの既定のテンプレートが(境界線の背景を明示的に赤にすることにより)背景のテンプレートバインディングを削除するため、スタイルのトリガは何の影響も与えません。

はおぼろげながら理解できる。


TriggerResource.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="{x:Type Button}" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Red"/>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
                <Setter Property="Background" Value="Blue" />
            </Trigger>
            <!--ボタンを押しても黄色にはならない-->
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Background" Value="Yellow"/>
            </Trigger>
        </Style.Triggers>
        
        
    </Style>

    <ControlTemplate TargetType="Button" x:Key="buttontemplate">
        <Border Background="{TemplateBinding Background}" x:Name="border">
            <ContentPresenter/>

        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Background" Value="Yellow" TargetName="border"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</ResourceDictionary>

trigger.xaml

<Window x:Class="useResource.trigger"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="trigger" Height="300" Width="300">
    <Grid>
        <Grid.Resources>
            <ResourceDictionary Source="TriggerResource.xaml"/>
        </Grid.Resources>

        <!--TemplateはButtonの属性として書く-->
        <Button Template="{StaticResource ResourceKey=buttontemplate}"/>

    </Grid>
</Window>