WPF

WPF テンプレート編集

2012年12月8日

WPF ではテンプレートを編集することで、簡単に見た目を変えることができます。今回は、RadioButton に Button の外観を設定してオプションボタンを作成してみます。 (エクセルにあるやつです。)

1.ExpressionBlend で RadioButton のテンプレートをコピーして編集します。
コンテキストメニューの「テンプレートの編集」 →「コピーして編集」

テンプレートを編集
テンプレートを編集

2.デフォルトで使われている BulletDecorator を Button コントロールに置き換えます。

<Window.Resources>
<SolidColorBrush x:Key="CheckBoxStroke" Color="#8E8F8F"/>
<Style x:Key="CheckRadioFocusVisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Margin="14,0,0,0"
SnapsToDevicePixels="true"
Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"
StrokeThickness="1"
StrokeDashArray="1 2"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type RadioButton}">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="Background" Value="#F4F4F4"/>
<Setter Property="BorderBrush" Value="{StaticResource CheckBoxStroke}" />
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RadioButton}">
<!-- デフォルトの BulletDecorator をコメントアウト -->
<!--<BulletDecorator>
<BulletDecorator.Bullet>
<Microsoft_Windows_Themes:BulletChrome
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
IsChecked="{TemplateBinding IsChecked}"
IsRound="true"
RenderMouseOver="{TemplateBinding IsMouseOver}"
RenderPressed="{TemplateBinding IsPressed}"/>
</BulletDecorator.Bullet>
<ContentPresenter
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</BulletDecorator>-->
<!-- 代わりに Button を配置 -->
<Button>
<Button.Content>
<ContentPresenter
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
RecognizesAccessKey="True"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Button.Content>
</Button>
<!-- 代わりに Button を配置 -->
<ControlTemplate.Triggers>
<Trigger Property="HasContent" Value="true">
<Setter Property="FocusVisualStyle" Value="{StaticResource CheckRadioFocusVisual}"/>
<Setter Property="Padding" Value="4,0,0,0"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<RadioButton GroupName="radio"
Content="A"
x:Name="radioButton1"
Height="30" Width="30" Margin="200,141,273,140" />
<RadioButton GroupName="radio"
Content="B"
x:Name="radioButton2"
Height="30" Width="30" Margin="236,141,237,140" />
<RadioButton GroupName="radio"
Content="C"
x:Name="radioButton3"
Height="30" Width="30" Margin="272,141,201,140" />
</Grid>

複数あるボタンから一つのみを選択することができます。RadioButton なので当然ですが ^^;

オプションボタン

-WPF