很多國際化的程序都提供了多語言的選項,這樣方便不同國家的使用者更方便的使用軟件。這篇博客中將介紹在WPF中實現多語言的方式。
方式一,使用WPF動態資源的方式實現。先簡單介紹下StaticResource和DynamicResource,這兩者的區別在於動態資源改變后會實時的體現出來,而靜態資源只加載一次,后面對資源的任何改變都不會體現出來。顯而易見,使用動態資源會降低系統的性能。
新建一個工程,添加ZH.xaml與EN.xaml兩個資源文件,用於放置界面顯示的文案;
MainWindow.xaml:
<Grid> <StackPanel> <TextBlock Text="{DynamicResource Greeting}"/> <Button Content="{DynamicResource Language}" Width="100" Height="35" Click="SwitchButton_Click"/> </StackPanel> </Grid>
切換語言方法:
private string _currentLan = string.Empty; public MainWindow() { InitializeComponent(); _currentLan = "ZH"; } private void SwitchButton_Click(object sender, RoutedEventArgs e) { string message = TryFindResource("Message") as string; MessageBox.Show(message); // TODO: 切換系統資源文件 ResourceDictionary dict = new ResourceDictionary(); if(_currentLan == "ZH") { dict.Source = new Uri(@"Resources\Language\EN.xaml", UriKind.Relative); _currentLan = "EN"; } else { dict.Source = new Uri(@"Resources\Language\ZH.xaml", UriKind.Relative); _currentLan = "ZH"; } Application.Current.Resources.MergedDictionaries[0] = dict; }
運行效果:
代碼點擊這里下載。
方式二,Xml文件+XPath的方式來實現。
項目結構:
新建兩個xml文件,Chinese.xml和English.xml。
<?xml version="1.0" encoding="utf-8"?> <language> <resources> <resource name="Greeting">你好 WPF世界!</resource> </resources> </language>
使用:
<TextBlock> <TextBlock.Text> <Binding Source="{StaticResource Lang}" XPath="resource[@name='Greeting']" /> </TextBlock.Text> </TextBlock>
切換語言:
private string _currentLang = string.Empty; public MainWindow() { InitializeComponent(); _currentLang = "Zh"; } private void SwitchButton_Click(object sender, RoutedEventArgs e) { // TODO: Switch Language XmlDataProvider provider = TryFindResource("Lang") as XmlDataProvider; if (provider == null) return; if(_currentLang == "Zh") { provider.Source = new Uri("Languages/English.xml", UriKind.Relative); _currentLang = "En"; } else { provider.Source = new Uri("Languages/Chinese.xml", UriKind.Relative); _currentLang = "Zh"; } provider.Refresh(); }
運行效果:
代碼點擊這里下載。
當然實現多語言的方式有很多方式,例如:
http://www.codeproject.com/Articles/35159/WPF-Localization-Using-RESX-Files
感謝您的閱讀。謝謝!