2012-02-03 21 views
2

如何添加ResourceDictionary像這樣dinamicly?如何加載外部XAML ResourceDictionary

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

與絕對的Uri它完美的工作,但從相對不。

+0

您是否在您的程序集運行在同一文件夾中有Design.xaml? – Kolja 2012-02-03 12:02:20

+0

是的,我真的有。 – Aldos 2012-02-03 12:06:16

回答

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); 

工作非常適合我。