我的UI由一组样式定义。
我想让用户从两个样式系列中进行选择。
如何在代码中替换全局样式?
答案 0 :(得分:3)
以下文章可能有所帮助:
通常,您需要在运行时使用来自其他程序集的新资源替换App.Resources.MergedDictionaries
,并在MainWindow
级别的列表中重新应用模板,请确保DynamicResource
为App.Resources.MergedDictionaries
你的风格设计。以下算法可以帮助您:
App.Resources.MergedDictionaries
ResourceDictionary
mainWindow.ApplyTemplate();
希望这有帮助。
答案 1 :(得分:3)
密切关注依赖关系,以便资源不会尝试引用尚未定义的其他资源。请参阅Merged Dictionaries部分,了解何时加载的内容。此外,您必须将所有资源从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
}