複数のコントロールに同じスタイルを適用する(StaticResource、BasedOn)
画面上に配置した複数のコントロール(ボタンやラベルなど)に同じスタイルを適用したいことがよくあるので、その方法についてです。
コード
以下は、複数のボタンに対して同じスタイルを適用するコードになります。ついでにBasedOnでスタイルの継承もしています。
<Window.Resources>
<Style x:Key="ButtonBase" TargetType="Button">
<Setter Property="FontSize" Value="16" />
<Setter Property="Width" Value="100" />
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="5" />
</Style>
<Style x:Key="ButtonRed" TargetType="Button" BasedOn="{StaticResource ButtonBase}">
<Setter Property="Foreground" Value="Red" />
</Style>
<Style x:Key="ButtonBlue" TargetType="Button" BasedOn="{StaticResource ButtonBase}">
<Setter Property="Foreground" Value="Blue" />
</Style>
</Window.Resources>
<Canvas>
<StackPanel>
<Button Content="ボタン1-1" Style="{StaticResource ButtonRed}"/>
<Button Content="ボタン1-2" Style="{StaticResource ButtonRed}"/>
<Button Content="ボタン2-1" Style="{StaticResource ButtonBlue}"/>
<Button Content="ボタン2-2" Style="{StaticResource ButtonBlue}"/>
</StackPanel>
</Canvas>