问题描述
我正在为我的应用添加复杂的主题。我的想法是当用户更改主题时,我加载一个 ResourceDictionary 并在运行时更改它的子项。 但是插入操作总是失败,请帮帮我。
以下是我所做的:
auto newResourceDic = ref new ResourceDictionary();
newResourceDic->Source = ref new Uri("ms-appx:///XAMLPages/test.xaml");
if (newResourceDic->HasKey(L"TitleBarColor"))
{
newResourceDic->Remove(L"TitleBarColor");
//It's a SolidColorBrush,I want to replace this brush to a more complex bitmapbrush
//For convenience,I use a solidcolorbrush instead
Windows::UI::Color c;
c.A = 255;
c.R = 255;
c.G = 0;
c.B = 0;
testbrush = ref new Windows::UI::Xaml::Media::SolidColorBrush(c);
//HRESULT:0x800F1000 No installed components were detected.
//WinRT information: Local values are not allowed in resource dictionary with Source set [Line: 0 Position: 0]
newResourceDic->Insert("TitleBarColor",testbrush);
}
解决方法
UWP,是否可以通过编程方式添加 ResourceDictionary 值?
当你更新 newResourceDic
时,它会抛出 Local values are not allowed in resource dictionary with Source set 异常,默认情况下,如果你想以编程方式添加 ResourceDictionary 值。我们建议您将 newResourceDic
添加到应用程序 ResourceDictionary.MergedDictionaries
中。然后使用 App.Current.Resources
更新,如下所示
Xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ms-appx:///TestResouce.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
C# 代码
if (App.Current.Resources.ContainsKey("TitleBarColor"))
{
App.Current.Resources["TitleBarColor"] = new SolidColorBrush(Colors.Red);
App.Current.Resources.Add("HighTitleBarColor",new SolidColorBrush(Colors.Bisque));
}
C++
if (App::Current->Resources->HasKey(L"TitleBarColor")) {
App::Current->Resources->Remove(L"TitleBarColor");
Windows::UI::Color c;
c.A = 255;
c.R = 255;
c.G = 0;
c.B = 0;
auto testbrush = ref new Windows::UI::Xaml::Media::SolidColorBrush(c);
App::Current->Resources->Insert("TitleBarColor",testbrush);
}