如何加载外部XAML ResourceDictionary

时间:2012-02-03 11:56:48

标签: c# xaml resourcedictionary

如何像这样动态添加ResourceDictionary?

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

凭借绝对的Uri,它完美地运作,但来自Relative does。

1 个答案:

答案 0 :(得分:1)

我使用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);

对我来说效果很好。