WPF動態(tài)資源使用方法介紹
WPF動態(tài)資源是一個比較龐大的數(shù)據(jù)資源。在這里我們就以一個范例為大家介紹一下有關(guān)WPF動態(tài)資源的相關(guān)應(yīng)用方法,希望對大家有所幫助。#t#
剛好公司在進行一個WPF的內(nèi)部項目,今天我的任務(wù)是讓整個應(yīng)用支持多語言(全球化)。我使用了WPF動態(tài)資源來存放mutil language數(shù)據(jù)。
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>
 
對于各個業(yè)務(wù)組件的全球化十分簡單,如
- <Button Height="23" Name="btnChina"
 - Width="75" Click="Button_Click"
 - Content="{DynamicResource China}">
 
但是對于主窗體來說,菜單是要通過讀取各個業(yè)務(wù)組件的CustomAttribute來創(chuàng)建的。起初,我用的方法是直接從應(yīng)用程序的WPF動態(tài)資源里找到對應(yīng)的串。
(string)Application.Current.Resources.MergedDictionaries[0][key] 但是問題隨之而來,當(dāng)我切換language resource文件時,菜單上的內(nèi)容并不會自動更新。既然WPF都用了DataBinding功能,總不能還用代碼去更新菜單項吧。這違背了我們程序員的原則!
查閱了相關(guān)書籍,終于找到了WPF動態(tài)資源解決的方案,使用UIElement對象的SetResourceReference方法來實現(xiàn){DynamicResource XXXX}的功能:
- item = new MenuItem();
 - item.SetResourceReference
 
(MenuItem.HeaderProperty, key);- this.menuMain.Items.Add(item);
 















 
 
 
 
 
 
 