VisualStateManager お試し

はじめに

VisualStateManager*1 を使って「マウスカーソルが上にあるときだけ Button の色を変更する」処理をコードレス(XAML は書くけど)で実現してみます。

XAML

<UserControl x:Class="VSMSample.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Button x:Name="button1" Content="さんぷる">

            <!-- Button のテンプレートを変更 -->
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <Grid>
                        <!--Button の背景色を緑にする-->
                        <Border x:Name="border1" BorderThickness="0" BorderBrush="Black" Background="Green" CornerRadius="20">
                            <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
                                <ContentPresenter Content="{TemplateBinding Content}" />
                            </Grid>
                        </Border>
                        <VisualStateManager.VisualStateGroups>

                            <!--必要なVisualStateだけを記述-->
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal"/>
                                
                                <!--Button の上にマウスカーソルがある時背景色を1秒かけて黄色にする-->
                                <VisualState x:Name="MouseOver">
                                    <Storyboard>
                                        <ColorAnimation
                                                Storyboard.TargetName="border1"
                                                Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
                                                To="Yellow"/>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                    </Grid>
                </ControlTemplate>
            </Button.Template>
        </Button>
    </Grid>
</UserControl>

実行画面

通常は
f:id:griefworker:20090107104157p:image
で、マウスカーソルを上に持っていくと
f:id:griefworker:20090107104225p:image
になります。

まとめ

VisualStateManager を使えば、WPF の Trigger と同じような事が出来ます。ただ、必要な VisualState だけ記述すれば良いとはいえ、Trigger ほど手軽じゃないのが難点ですね。

*1:コントロールの状態を遷移するための状態とロジックを管理するクラス