WPFプログラミング備忘録

WPF マウスオーバー時にボタンの配色を変える方法

WPF

WPFのボタンコントロールでマウスオーバーした時に背景色と前景色(今回は文字色)を変える方法をまとめておきます。背景色にそれぞれ赤色、青色、黄色および文字色に黒色の3つのボタンを用意します。これらのボタンのマウスオーバー時には背景色をダークグレーに文字色を白色に変更します。今回は以下の通りxamlファイル内でリソースにControlTemplateを定義しました。

<Window x:Class="WpfStudyApp.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:WpfStudyApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="250" Width="400">
    <Window.Resources>
        <ControlTemplate x:Key="btnTemplate"
                         TargetType="Button">
            <Border Name="border"
                BorderThickness="3"
                BorderBrush="DarkGray"
                Background="{TemplateBinding Background}"
                CornerRadius="10">
                <ContentPresenter VerticalAlignment="Center"
                                  HorizontalAlignment="Center" />
            </Border>

            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter TargetName="border"
                            Property="Background"
                            Value="DarkGray" />
                    <Setter Property="Foreground"
                            Value="White" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <Button Height="30"
                    Width="120"
                    Margin="10"
                    Content="赤色ボタン"
                    Background="Red"
                    Template="{StaticResource btnTemplate}"
            />
            <Button Height="30"
                    Width="120"
                    Margin="10"
                    Content="青色ボタン"
                    Background="Blue"
                    Template="{StaticResource btnTemplate}"
            />
            <Button Height="30"
                    Width="120"
                    Margin="10"
                    Content="黄色ボタン"
                    Background="Yellow"
                    Template="{StaticResource btnTemplate}"
            />
        </StackPanel>
    </Grid>
</Window>

ビルドして実行します。

マウスオーバーしていない時は以下のとおりです。

青色のボタンにマウスオーバーすると以下のように配色が変わります。他のボタンも同様です。

今回はButtonコントロールの部品構成が事前にわかっていることが必要でした。知らなかったり忘れてしまっている場合もあるでしょう。このようなときはVisual Studioの機能を使ってコントロールのテンプレートを自動生成させることができます。これについては以下の記事で確認しています。

以上です。

コメント