Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

テーマを適用する

アプリ実行

起動


チェックする


チェックを外す


ソースコード

App.xaml
<Application x:Class="WpfApplication7.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
</Application>
MainWindow.xaml
<Window x:Class="WpfApplication7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="100" Width="150">
    <StackPanel>
        <CheckBox
            x:Name="checkBox"
            IsChecked="False"
            Checked="checkBox_Checked"
            Unchecked="checkBox_Checked">
            カスタムボタンを使用しますか?
        </CheckBox>
        <Button
            Margin="2"
            HorizontalAlignment="center">
            ボタン
        </Button>
    </StackPanel>
</Window>
MainWindow.xaml.cs
using System;
using System.Windows;

namespace WpfApplication7 {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
        }

        private void checkBox_Checked(object sender, RoutedEventArgs e) {
            // ボタンのリソースをこのウィンドウのリソースにマージする
            if (checkBox.IsChecked ?? false)
                MergeDictionary(this.Resources, "CustomButtons.xaml");
            else
                MergeDictionary(this.Resources, "DefaultButtons.xaml");
        }

        private void MergeDictionary(ResourceDictionary dictionary, string themeFileName) {
            ResourceDictionary theme = Application.LoadComponent(
                new Uri(themeFileName, UriKind.Relative)) as ResourceDictionary;

            dictionary.MergedDictionaries.Add(theme);
        }
    }
}
DefaultButtons.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="{x:Type Button}" TargetType="{x:Type Button}">
    </Style>
</ResourceDictionary>
CustomButtons.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="{x:Type Button}" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Red" />
    </Style>
</ResourceDictionary>