WPF

WPF Template を編集して Button コントロールの見た目をカスタマイズ

2014年11月15日

WPF では Template プロパティを書き換えることで、デフォルトの見た目を大きくカスタマイズすることができるようになっています。
ここでは Template プロパティを使って Button コントロールに画像を埋め込んでみます。なお、Visual Studio のバージョンは 2013 です。

1.Button コントロールを右クリックし、「テンプレートの編集」→「コピーして編集」を選択します。

2.「Style リソースの作成」ダイアログが表示されるので、「OK」をクリックします。

3.ButtonStyle1 というキーを持つ、Button をターゲットとするスタイルが生成されますので、<Setter Property="Template"> という箇所を探し出します。<Setter Property="Template"> には外観や振る舞いが記述されています。<ControlTemplate TargetType="{x:Type Button}"> 内に外観が定義されていて、contentPresenter というキーを持つ ContentPresenter 内にボタンのテキスト部分が定義されていますので、この ContentPresenter の横に画像を配置していきます。

編集前:

<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
...

編集後:
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<StackPanel Orientation="Horizontal">
<Image Source="BlueRect.PNG" Width="13px"/>
<ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</StackPanel>
</Border>
...


実行結果:

今回は単純にボタン内の横に四角い画像を埋め込んだだけでしたが、Template プロパティを利用して様々なユーザーコントロールの見た目を自由にカスタマイズでき、Windows Forms では実現することのできないような柔軟なカスタマイズを行うことができます。

-WPF