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

时间:2011-09-13 10:39:28

标签: 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>

ResDictNormal.xaml中的相同样式是:

<Style x:Key="StyleTitleText" TargetType="TextBlock">
    <Setter Property="FontFamily" Value="Tahoma" />
    <Setter Property="FontSize" Value="14"/>
    <Setter Property="Foreground" Value="WhiteSmoke" />
</Style>

我将xaml中的文本块设置为:

 <TextBlock Style="{DynamicResource StyleTextblock}" Text="Prod.Code" VerticalAlignment="Top" />

我想在运行时在这些样式之间切换。我的工作是这样的:

           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;

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

1 个答案:

答案 0 :(得分:4)

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

另请注意,如果主题需要动态更新UI(例如,无需重新加载整个UI),则可能需要使用DynamicResource而不是StaticResource

如果有帮助,请告诉我。

相关问题