如何像这样动态添加 ResourceDictionary?
ResourceDictionary template = new ResourceDictionary();
template.Source = new Uri("Design.xaml", UriKind.Relative);
Application.Current.Resources.MergedDictionaries.Add(template);
对于绝对 Uri,它可以完美地工作,但对于 Relative 则不能。
最佳答案
我使用 XamlReader 类来执行此操作:
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);
对我来说效果很好。
关于c# - 如何加载外部 XAML ResourceDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9128287/