WPF EventTrigger の利用方法を紹介します。
EventTrigger とは
EventTrigger は、UI 上で何らかの操作が行われた際に、対応するイベントを XAML 上で表現することのできる機能です。例えば、ボタンがクリックされたタイミングで何らかの処理を行う、などです。Windows Forms であれば、コードビハインドでボタンクリックに対応するイベントハンドラーを書き、そのイベントハンドラー内に手続き的に処理を記述しますが、WPF の EventTrigger を利用することで、このようなイベント処理を、XAML 上で完結して記述することができます。
EventTrigger 実装例
続いて、EventTrigger の実装例を紹介します。ここでは、下記の処理を行うように EventTrigger を実装しています。
①ボタンをクリックしたタイミングで Wave ファイルを再生
②マウスホバー中はボタンを高く、ホバーをやめるとボタンの高さを戻す
<Window x:Class="EventTrigger.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="Button">
<Style.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<SoundPlayerAction Source="beach.wav"/>
</EventTrigger>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation To="300" Duration="0:0:2"
Storyboard.TargetProperty="Height" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="MouseLeave">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Duration="0:0:2"
Storyboard.TargetProperty="Height" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Button Content="Button" Height="23" Name="button1" Width="75" />
</Grid>
</Window>