在後端程式碼中動態載入 XAML 能賦予 WPF 應用程式極大彈性,支援多語系切換、主題變更、動態文檔生成等進階功能。本文介紹三種常用方法。

Application.Current.Resources.MergedDictionaries.Insert(0,
Application.LoadComponent(new Uri("abc/Index.xaml", UriKind.Relative)) as ResourceDictionary);
僅限專案內建置為 Resource 的 XAML 檔案,外部檔案會提示找不到。
Application.Current.Resources.MergedDictionaries.Insert(0,
XamlReader.Load(new FileStream(@"C:\index.xaml", FileMode.Open)) as ResourceDictionary);
適用於專案外部的 XAML 資源檔,實現外掛式樣式/範本載入。
XamlReader.Parse(@"<FlowDocument xmlns='https://schemas.microsoft.com/winfx/2006/xaml/presentation'>
<Paragraph><Run>Hi!</Run></Paragraph></FlowDocument>") as FlowDocument
直接將 XAML 字串轉為對應物件(如 FlowDocument),需 .NET 3.5 SP1 以上支援。早期版本需使用 XamlReader.Load 多載。
掌握這三種技巧,能讓 WPF 程式在資源管理與物件生成上更具彈性與擴充性。