WPF 多语言实现

很多国际化的程序都提供了多语言的选项,这样方便不同国家的使用者更方便的使用软件。这篇博客中将介绍在WPF中实现多语言的方式。

方式一,使用WPF动态资源的方式实现。先简单介绍下StaticResource和DynamicResource,这两者的区别在于动态资源改变后会实时的体现出来,而静态资源只加载一次,后面对资源的任何改变都不会体现出来。显而易见,使用动态资源会降低系统的性能。.

新建一个工程,添加ZH.xaml与EN.xaml两个资源文件,用于放置界面显示的文案;

WPF 多语言实现

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;        }

运行效果:

WPF 多语言实现

代码点击这里下载。

方式二,Xml文件+XPath的方式来实现。

项目结构:

WPF 多语言实现

新建两个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();        }

运行效果:

WPF 多语言实现