スタイル定義とは?
WPFではコントロールごとにデフォルトのスタイルを定義することができます。例えばラベルの背景色は「青」、文字の色は「白」という風に決めておくと、どの画面でラベルを生成しても、同じ背景色や文字の色で表示されることになり、アプリケーション全体に統一感を持たすことができます。
スタイル定義の書き方
WPFのプロジェクトを作成したときに、自動で生成されるApp.xamlファイルのApplication.Resourcesエリアに、Style TargetType=”Label”という感じで記述します。”Label”の部分は、スタイルを設定したコントロール名を指定します。そのあとにSetter Propertyでプロパティ名を指定し、Value=に値を指定します。
<Application.Resources> <Style TargetType="Label"> <Setter Property="Background" Value="DarkBlue"/> </Style> </Application.Resources>
個別で異なる設定をしたい場合
Styleで指定した値はデフォルト値になるので、画面に指定するコントロールに特に指定しなければ、デフォルト値で動作しますが、場合によっては、個別で背景色などを変更したい場合などがよくあります。そういった場合は、Xamlでコントロールを指定するときに背景色などを指定すれば、上書きでプロパティの値が設定されるため、個別での異なる設定が可能です。
サンプルコード
次の例ではLabelを3個、Buttonを3個設置し、Application.Resourcesのスタイル設定がどのように機能しているかを確認できます。
<Application x:Class="WPF007.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPF007" StartupUri="MainWindow.xaml"> <Application.Resources> <Style TargetType="Label"> <Setter Property="Background" Value="DarkBlue"/> <Setter Property="Foreground" Value="Yellow"/> <Setter Property="FontSize" Value="25"/> </Style> <Style TargetType="Button"> <Setter Property="Background" Value="DarkGray"/> <Setter Property="Foreground" Value="White"/> <Setter Property="FontSize" Value="20"/> </Style> </Application.Resources> </Application>
Label用のスタイルとButton用のスタイルを作成し、それぞれ背景色、文字色、フォントサイズを指定しています。
<Window x:Class="WPF007.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WPF007" mc:Ignorable="d" Title="MainWindow" Height="300" Width="300"> <Grid> <StackPanel> <Label Content="A1"/> <Label Content="A2" Background="Green" Foreground="Red" FontSize="40"/> <Label Content="A3"/> <Button Content="B1"/> <Button Content="B2" Background="DarkCyan"/> <Button Content="B3"/> </StackPanel> </Grid> </Window>
LabelとButtonを3個設置していますが、背景色、文字色、フォントサイズを指定していないコントロールは、Application.Resourcesで設定したそれぞれの値になり、背景色などを指定したコントロールは、それぞれ指定した値に上書きされていることが確認できます。