主流方法参考博客:(虽然老了点但是有用)
但是默认的方案里试用静态资源不能动态切换语言,以下是动态切换语言的方法,可以在运行时切换语言。
初步配置
在文件夹中新建资源文件,比如Resources/zh.xaml
和Resources/en.xaml
文件内容如下:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WPFMultiLanguage.Resources.Language">
<system:String x:Key="Testing">Testing...</system:String>
</ResourceDictionary>
在app.xaml中添加此文件为资源,添加一个就行了,作为默认语言。最终app.xaml
差不多是这样的:
<Application
x:Class="DeviceInfoSyncClient.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
DispatcherUnhandledException="OnDispatcherUnhandledException"
Exit="OnExit"
Startup="OnStartup">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!--Default Language File-->
<ResourceDictionary Source="/DeviceInfoSyncClient;component/Resources/en_us.xaml"/>
-------其他的资源文件
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
在程序中使用时,需要在xaml中获取的话,需要使用DynamicResource
以应对动态修改,如下所示:
<Grid>
<StackPanel>
<TextBlock Text="{DynamicResource Greeting}"/>
<Button Content="{DynamicResource Language}" Width="100" Height="35" Click="SwitchButton_Click"/>
</StackPanel>
</Grid>
在cs文件中动态获取的话,就直接
(string)Application.Current.FindResource("Testing")
动态切换
因为已经将一个文件作为资源字典了,其他的语言的资源文件没有用到,这里需要动态替换一下:
public static void ChangeLanguage(string newLang)
{
ResourceDictionary dict = new ResourceDictionary();
//下面换成你想要的资源字典
dict.Source = new Uri(@"Resources\zh_cn.xaml", UriKind.Relative);
Application.Current.Resources.MergedDictionaries[0] = dict;
}
近期评论