WPF Tips - Material Designにする


概要

WPFアプリを作成する際に、Material Designにしようと思うんですが、
毎回忘れるので、備忘録として記事を作成(笑)。

手順

WPFプロジェクトを作成し、ソリューションエクスプローラ上でプロジェクトを右クリック。
メニューから「NuGetパッケージの管理」を選択します。

次に、参照タブを選び、検索枠に「MaterialDesign」と入力。
検索結果から「MaterialDesignThemes」を選択。
右側に情報が表示されるので、「インストール」をクリック

以下のようなダイアログが表示されるので、OKをクリック。

インストールが完了したら、App.xmalを開きます。Application.Resourceタグの中に、以下を記述します。

App.xmal
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.lightgreen.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.amber.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

MainWindow.xamlのWindowタグ内に以下のパラメータを追加します。

MainWindow.xaml
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        Background="{DynamicResource MaterialDesignPaper}"
        FontFamily="{DynamicResource MaterialDesignFont}"

設定は以上で完了。
試しにMainWindow.xamlにボタンを配置してみます
以下のようなコードを書いてみました。

    <Grid>
        <StackPanel Margin="10,10,0,0" VerticalAlignment="Top" Orientation="Horizontal" >
            <Button x:Name="SettingButton"
                        Margin="10">
                <StackPanel Orientation="Horizontal">
                    <materialDesign:PackIcon Kind="Settings" />
                    <TextBlock Margin="8 0 0 0" VerticalAlignment="Center">
                            設定
                    </TextBlock>
                </StackPanel>
            </Button>
        </StackPanel>
    </Grid>

実行結果はこんな感じ