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

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

3.ButtonStyle1 というキーを持つ、Button をターゲットとするスタイルが生成されますので、
編集前:
<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 では実現することのできないような柔軟なカスタマイズを行うことができます。
💬 コメント