.Net Framework WPF

WPF Trigger 実装例

2017年11月19日

WPF Trigger の実装例です。

Button の Content の値に応じて Button の背景色を赤色に変更します。また、Button にマウスがホバーしている間、Button の文字色を白色に変更します。

<Window x:Class="TriggerDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:TriggerDemo"
    mc:Ignorable="d" Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="button1" Height="30" Width="200">
            <Button.Resources>
                <Style TargetType="Button">
                    <Style.Triggers>
                        < !--Content が "button1"ならば-->
                        <Trigger Property="Content"Value="button1">
                            < !--背景色を赤色に変更-->
                            <Setter Property="Background"Value="Red"/>
                        </Trigger>
                        < !--Button 上にマウスがホバーしていたら-->
                        <Trigger Property="IsMouseOver"Value="True">
                            < !--前景色を白色に変更-->
                            <Setter Property="Foreground"Value="White"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Button.Resources>
        </Button>
    </Grid>
</Window>

関連情報:

WPF DataTrigger 実装例
http://kainobi2.blogspot.jp/2017/05/wpf-datatrigger.html

-.Net Framework, WPF