I'm working on adding complex theme for my app. What I thought is when users changes theme, I load a ResourceDictionary and changes it's children at runtime. But insert operation always fail, please help me.
Following is what I did:
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, is it possible to add ResourceDictionary value programmatically?
When you update above newResourceDic
, it will throw Local values are not allowed in resource dictionary with Source set exception, it's by default, if you want to add ResourceDictionary value programmatically. We suggest you add newResourceDic
into App ResourceDictionary.MergedDictionaries
. Then update with App.Current.Resources
like the following
Xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ms-appx:///TestResouce.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
C# code
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);
}
User contributions licensed under CC BY-SA 3.0