删除资源字典并在WPF中添加另一个字典

son*_*ony 6 wpf xaml

我有两个资源词典.一个叫做ResDictGlass.xaml,另一个叫做ResDictNormal.xaml.两者都具有相同的属性和不同的值.例如

ResDictGlass.xaml有一个这样的样式:

<Style x:Key="StyleTitleText" TargetType="TextBlock">
    <Setter Property="FontFamily" Value="Arial" />
    <Setter Property="FontSize" Value="14"/>
    <Setter Property="Foreground" Value="Green" />
</Style>
Run Code Online (Sandbox Code Playgroud)

ResDictNormal.xaml中的相同样式是:

<Style x:Key="StyleTitleText" TargetType="TextBlock">
    <Setter Property="FontFamily" Value="Tahoma" />
    <Setter Property="FontSize" Value="14"/>
    <Setter Property="Foreground" Value="WhiteSmoke" />
</Style>
Run Code Online (Sandbox Code Playgroud)

我在xaml中设置了textblock:

 <TextBlock Style="{DynamicResource StyleTextblock}" Text="Prod.Code" VerticalAlignment="Top" />
Run Code Online (Sandbox Code Playgroud)

我想在运行时切换这些样式.我做的是这样的:

           case "normal":
               ResourceDictionary ResDict1 = new ResourceDictionary();
               ResDict1.Source = new Uri("/ResDictNormal.xaml", UriKind.RelativeOrAbsolute);
               Application.Current.Resources.MergedDictionaries.Add(ResDict1);
               break;

           case "flip":
               ResourceDictionary ResDict2 = new ResourceDictionary();
               ResDict2.Source = new Uri("/ResDictGlass.xaml", UriKind.RelativeOrAbsolute);
               Application.Current.Resources.MergedDictionaries.Add(ResDict2);
               break;
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?我们是否必须删除当前字典然后添加字典?

WPF*_*-it 6

是的,您希望将两个词典中的任何一个合并到应用程序中,而不是两者都合并。否则模棱两可的资源将在引用时抛出错误。

还请记住,如果主题需要动态更新 UI(即无需重新加载整个 UI),您可能需要使用DynamicResourceover StaticResource

如果这有帮助,请告诉我。