1

我的 UI 由一组样式定义。

我想让用户从两个样式系列中进行选择。

如何在代码后面换出全局样式?

4

2 回答 2

3

以下文章可能会有所帮助:

通常,您需要将App.Resources.MergedDictionaries运行时中的新资源替换为可能来自另一个程序集的新资源,并在 级别的列表中重新应用模板,请MainWindow确保DynamicResource在您的样式分配中具有。以下算法可能会对您有所帮助:

  1. 干净的App.Resources.MergedDictionaries
  2. 填充App.Resources.MergedDictionaries新的一组ResourceDictionary
  3. 重新应用窗口模板mainWindow.ApplyTemplate();

希望这可以帮助。

于 2012-12-06T08:38:43.183 回答
3

密切注意依赖关系,这样资源就不会尝试引用另一个尚未定义的资源。请参阅有关合并字典的部分以查看何时加载的内容。此外,您必须将所有资源从 App.xaml 移动到您的通用资源字典中,因为当您将应用程序资源重置为新的合并字典时,它们将被清除。

更新似乎仅在重新创建元素时生效,因此需要导航来应用更改。

private void LoadStyles(StyleType styleType)
{
    ResourceDictionary merged = new ResourceDictionary();
    ResourceDictionary generic = new ResourceDictionary();
    ResourceDictionary theme = new ResourceDictionary();

    generic.Source = new Uri("ms-appx:/Common/StandardStyles.xaml");

    switch (styleType)
        {
            default:
            case StyleType.Custom1: { theme.Source = new Uri("ms-appx:/Common/AppStyles-Custom1.xaml"); break; }
            case StyleType.Custom2: { theme.Source = new Uri("ms-appx:/Common/AppStyles-Custom2.xaml"); break; }
            case StyleType.Custom3: { theme.Source = new Uri("ms-appx:/Common/AppStyles-Custom3.xaml"); break; }
        }

    merged.MergedDictionaries.Add(generic);
    merged.MergedDictionaries.Add(theme);

    App.Current.Resources = merged;

    //this.ApplyTemplate(); <- doesn't seem to reapply resources to layout tree
}
于 2012-12-06T19:49:54.357 回答