c# - 如何加载外部 XAML ResourceDictionary

标签 c# xaml resourcedictionary

如何像这样动态添加 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/

相关文章:

c# - 使用嵌套资源字典动态更改 wpf 中的主题

c# - 推特 API : Self-login

c# - 无法用鼠标选择 TextBox 控件的文本

c# - 聚合根通过ID引用另一个聚合根,如何使用RavenDB保持完整性?

.net - 允许非开发人员定义 Workflow Foundation 4 流程的解决方案

c# - ListBox 的 SelectionChanged 事件第二次不起作用

c# - 有什么方法可以设置 ResourceDictionary 键以匹配类名?

c# - 使用具有行+列坐标的值集合动态填充数据网格

wpf - 如何在 WPF 中创建按钮数组?

c# - 来自外部 ResourceDictionary 的对象