XAML Advent Calendar 2014 15日目担当のいっちゅうです。
またしても小物Tipsですが許してください。
ボタンをコントロールテンプレートで定義して画像をテンプレート外から指定する方法です。
↓こんな感じ。
まず
<Page.Resources>
に以下のソースをコピペしておきます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<controltemplate TargetType="Button" x:Key="ButtonTemplate"> <grid x:Name="grid" Background="Gray" Width="40" Height="40" HorizontalAlignment="Left" VerticalAlignment="Top"> <visualstatemanager .VisualStateGroups> <visualstategroup x:Name="CommonStates"> <visualstate x:Name="Normal"></visualstate> <visualstate x:Name="Pressed"> <storyboard> <coloranimation Duration="0" To="Black" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="grid" d:IsOptimized="True"></coloranimation> </storyboard> </visualstate> <visualstate x:Name="Disabled"> <storyboard> <coloranimation Duration="0" To="#FF4B4B4B" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="grid" d:IsOptimized="True"></coloranimation> </storyboard> </visualstate> <visualstate x:Name="PointerOver"> <storyboard> <coloranimation Duration="0" To="#FF5D5D5D" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="grid" d:IsOptimized="True"></coloranimation> </storyboard> </visualstate> </visualstategroup> </visualstatemanager> <image Width="32" Height="32" Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}" Margin="0"></image> </grid> </controltemplate> |
PageのXAMLにはこんな感じで書けばテンプレートを適用してくれます。
1 |
<button x:Name="btn_Input" MinWidth="40" MinHeight="40" Width="40" Height="40" Template="{StaticResource ButtonTemplate}" Content="/Assets/xxxx.png" Click="btn_Input_Click"></button> |
ポイントは「Content=”/Assets/xxxx.png”」です。
テンプレート内で「Source=”{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}」
と書くと、テンプレート外でContentに記述した画像ソースをバインディングできます。
テンプレートにある「visualstatemanager」はマウスオーバーやクリック時に背景色を変えています。
動きは普通のボタンコントロールとほぼ同じです。
後は画像を変えてどんどんボタンを作ることが出来ます。
では、明日はストアアプリで2chブラウザSankaを作っているideaki19さんです。