在运行时更改资源字典源(更改材料设计主题)

我在wpf中使用Material design。我在运行时更改主题(亮/暗)。这项工作正确。但是我在主窗口中使用Dialoghost这样的代码

    <Window x:Class="MyWPF.MainWindow"
    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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    Background="{Dynamicresource MaterialDesignPaper}"
    TextElement.Foreground="{Dynamicresource MaterialDesignBody}">
<materialDesign:DialogHost Identifier="RootDialog">
  <Grid>
     <!--some code-->
  </Grid>
</materialDesign:DialogHost>

我的dialoghost内容使用一些usercontrol,在usercontol中,我使用materialDesign:Card。但黑暗主题在Card中不起作用。所以我像这样对DialogHost使用resourcedictionary

<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>

且此方法正确,但是当我的主题是黑暗时。当我更改主题时,应更改此行。

<ResourceDictionary Source="pack://application:,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.light.xaml" />

但是我想在运行时更改主题是不可能的。当我这样写的时候,第二行开始运行,没有帮助。

<ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="pack://application:,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.dark.xaml" />
      <ResourceDictionary Source="pack://application:,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.light.xaml" />
</ResourceDictionary.MergedDictionaries>

然后以这种方式进行测试。

ResourceDictionary ResourceDic = new ResourceDictionary();
if (BoolValue)
      ResourceDic.Source = new Uri("pack://application:,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.dark.xaml",UriKind.RelativeOrAbsolute);
else
      ResourceDic.Source = new Uri("pack://application:,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.light.xaml",UriKind.RelativeOrAbsolute);
Application.Current.Resources.MergedDictionaries.Add(ResourceDic);

但是我不知道如何为它定义typeof(MaterialDesign:Card),我也不知道 如何将其用于UserControl。 请帮助我。如何在运行时做到这一点?

gk77338869 回答:在运行时更改资源字典源(更改材料设计主题)

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3161712.html

大家都在问