简体   繁体   中英

How to load external XAML ResourceDictionary

How can I add ResourceDictionary dinamicly like this?

ResourceDictionary template = new ResourceDictionary();
template.Source = new Uri("Design.xaml", UriKind.Relative);
Application.Current.Resources.MergedDictionaries.Add(template);

With absolute Uri it working perfectly but from Relative doesnt.

I use the XamlReader class to do this:

string exeFilePath = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;
string exeDirPath = Path.GetDirectoryName(exeFilePath);
string targetFile = "subfolder\\dictionary.xaml";
string path_to_xaml_dictionary = new Uri(Path.Combine(exeDirPath, targetFile)).LocalPath;
string strXaml = File.ReadAllText(path_to_xaml_dictionary);                    
ResourceDictionary resourceDictionary = (ResourceDictionary)XamlReader.Parse(strXaml);
Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);

Works pretty well for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM