WPF動態資源使用方法介紹
WPF動態資源是一個比較龐大的數據資源。在這里我們就以一個范例為大家介紹一下有關WPF動態資源的相關應用方法,希望對大家有所幫助。#t#
剛好公司在進行一個WPF的內部項目,今天我的任務是讓整個應用支持多語言(全球化)。我使用了WPF動態資源來存放mutil language數據。
resource文件如下:
- <ResourceDictionary xmlns="http:
//schemas.microsoft.com/winfx/
2006/xaml/presentation" - xmlns:x="http://schemas.microsoft.
com/winfx/2006/xaml" xmlns:sys=
"clr-namespace:System;assembly
=mscorlib"> - <sys:String x:Key="AllNews">
- 所有
- </sys:String>
- <sys:String x:Key="China">
- 中國
- </sys:String>
- <sys:String x:Key="World">
- 世界
- </sys:String>
- <sys:String x:Key="News">
- 新聞
- </sys:String>
- <sys:String x:Key="Other">
- 其他
- </sys:String>
- </ResourceDictionary>
對于各個業務組件的全球化十分簡單,如
- <Button Height="23" Name="btnChina"
- Width="75" Click="Button_Click"
- Content="{DynamicResource China}">
但是對于主窗體來說,菜單是要通過讀取各個業務組件的CustomAttribute來創建的。起初,我用的方法是直接從應用程序的WPF動態資源里找到對應的串。
(string)Application.Current.Resources.MergedDictionaries[0][key] 但是問題隨之而來,當我切換language resource文件時,菜單上的內容并不會自動更新。既然WPF都用了DataBinding功能,總不能還用代碼去更新菜單項吧。這違背了我們程序員的原則!
查閱了相關書籍,終于找到了WPF動態資源解決的方案,使用UIElement對象的SetResourceReference方法來實現{DynamicResource XXXX}的功能:
- item = new MenuItem();
- item.SetResourceReference
(MenuItem.HeaderProperty, key);- this.menuMain.Items.Add(item);