エンジニアの備忘録

エンジニアの私が備忘録や思ったことをちょいちょい書いてます。

C# WPF-Tips-スタイルシート外出し

StyleSheetとは

XAMLに記載しているコンポーネントのデザインや設定を
StyleSheetに記載してそれらを一括管理することです。

同じ設定を数カ所に記載するよりも、
一箇所にまとめて一箇所を更新する方が非常に便利です。

XAMLの設定

XAMLのResourceDictionaryに設定します。
パスは相対パスです。

<Window x:Class="StockData.View.StockDataView"
        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:vali="clr-namespace:StockData.Validation"
        mc:Ignorable="d"
        Title="StockData" Height="400" Width="450"
        Icon="/img/icon.png">
    <Window.Resources>
        <ResourceDictionary Source="./Style.xaml"/>
    </Window.Resources>

StyleSheetの追加

"リソースディクショナリ(WPF)"を選択し、任意の名前を付けます。
f:id:dasuma20:20191119215143p:plain


Styleシートの書き方

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:StockData.View">
    <Style x:Key="LabelStyle" TargetType="Label">
        <Setter Property="FontFamily" Value="Meiryo"/>
    </Style>
    <Style x:Key="ButtonStyle" TargetType="Button">
        <Setter Property="FontFamily" Value="Meiryo"/>
        <Setter Property="Margin" Value="20, 0, 0, 0"/>
    </Style>
</ResourceDictionary>

ButtonとLabelのStyleです。

x:Key

XAMLで使用する時の名前

TargetType

指定するStyleのコンポーネント

Setter

実際に設定するデザイン
Property、Valueコンポーネントによって様々です。


XAMLでのStyleの使い方

<Label Content="Start : "
            Style="{StaticResource LabelStyle}"/>

キーの設定

Style="{StaticResource キー}"

Styleの種類はたくさんあるので、実際に使い始めると難しさを再認識します・・・