LoginSignup
3
3

WPF + MaterialDesign in XAML + MahApps.Metroでダークテーマ動的切り替え

Posted at

有用な情報がぜんぜん見つからなかったので共有。

WPFアプリケーションにおいて、デザインフレームワークにMaterialDesignInXAMLToolkit(以下 MD)とMahApps.Metro(以下 Metro)を組み合わせて使っている場合のライト・ダークテーマ切り替えの実装。

コード

using System.Windows;
using ControlzEx.Theming;
using MaterialDesignThemes.Wpf;

private void ToggleTheme(bool isDark)
{
    ToggleMetroTheme(isDark);
    ToggleMdTheme(isDark);
}

// MaterialDesignのテーマを切り替える
private void ToggleMdTheme(bool isDark)
{
    var pallet = new PaletteHelper();
    ITheme theme = pallet.GetTheme();
    IBaseTheme baseTheme = isDark
        ? new MaterialDesignDarkTheme()
        : (IBaseTheme)new MaterialDesignLightTheme();

    theme.SetBaseTheme(baseTheme);
    pallet.SetTheme(theme);
}

// Metroのテーマを切り替える
private void ToggleMetroTheme(bool isDark)
    => ThemeManager.Current.ChangeTheme(
        Application.Current,
        isDark ? "Dark.Steel" : "Light.Steel");

既知の問題

MDとMetroを組み合わせて使う場合以下のように、App.xamlで「Metroが使用するSolidColorBrushをMDのもので置き換える」ということをしているハズ。

<ResourceDictionary.MergedDictionaries>
    <!-- MahApps -->
    <!-- 略 -->
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Themes/Light.Violet.xaml" />

    <!-- Material Design -->
    <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.BlueGrey.xaml" />
    <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />

    <!-- Material Design: MahApps Compatibility -->
    <!-- 略 -->
</ResourceDictionary.MergedDictionaries>

<!-- MahApps Brushes -->
<SolidColorBrush x:Key="MahApps.Brushes.Highlight"
                 Color="{DynamicResource Primary700}" />
<SolidColorBrush x:Key="MahApps.Brushes.AccentBase"
                 Color="{DynamicResource Primary600}" />
<SolidColorBrush x:Key="MahApps.Brushes.Accent"
                 Color="{DynamicResource Primary500}" />
<!-- 以下略 -->

のであるが、コードからMetroのテーマを上書きするので、タイトルバーの色がMetroのものに戻ってしまう。
コードから再度MDの色を取得してきて上書きすればよいのだが……正直もうめんどくさい。
ハナからMDとMetroとで統合の取れる色を決めておきましょう。
妙案あれば教えて下さい。

3
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3