【问题标题】:Change Resource Dictionary in runtime在运行时更改资源字典
【发布时间】:2019-11-27 07:45:18
【问题描述】:

我在我的 wpf 中使用 Material Design。我在运行时更改主题(浅色/深色)。

<materialDesign:DialogHost Identifier="RootDialog">
  <materialDesign:DialogHost.Resources>
    <Style TargetType="materialDesign:Card" BasedOn="{StaticResource {x:Type materialDesign:Card}}">
        <Style.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.dark.xaml" />
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Style.Resources>
        <Setter Property="Background" Value="{DynamicResource MaterialDesignCardBackground}" />
    </Style>
  </materialDesign:DialogHost.Resources>
  <Grid>
      <!--some code-->
  </Grid>
</materialDesign:DialogHost>

我想在运行时将资源字典的来源更改为

pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.light.xaml

我该怎么做?

【问题讨论】:

    标签: wpf resources material-design runtime resourcedictionary


    【解决方案1】:

    在 App.xaml 中定义您的资源字典应用范围

    <Application.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <!-- This is the default theme (useful for Designing)-->
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.dark.xaml"/>
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Application.Resources>
    

    在后面的代码中更改主题。

    public Skin ChangeSkin()
            {
                // you might want to have some logic here to keep switching
     ApplyResources("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.light.xaml")
            }
    
    private void ApplyResources(string src)
            {
                App a = App.Current as App;
                var dict = new ResourceDictionary() { Source = new Uri(src, UriKind.Relative) };
                foreach (var mergeDict in dict.MergedDictionaries)
                {
                    a.Resources.MergedDictionaries.Add(mergeDict);
                }
    
                foreach (var key in dict.Keys)
                {
                    a.Resources[key] = dict[key];
                }
            }
    

    【讨论】:

    • 我希望在materialDesign:Card 上设置此更改,因为更改正确,MainWindow's Cards 中也是如此,但DialogHost 中没有更改
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多