WPF 实际国际化多语言界面

2023-03-11,,

前段时候写了一个WPF多语言界面处理,个人感觉还行,分享给大家.使用合并字典,静态绑定,动态绑定.样式等东西

效果图

定义一个实体类LanguageModel,实际INotifyPropertyChanged接口

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel; namespace WpfApplication1
{
public class LanguageModel : INotifyPropertyChanged
{
private string _languageCode;
private string _languageName;
private string _languageDisplayName;
private string _resourcefile;
private bool _languageenabled;
/// <summary>
/// 语言代码 如en,zh
/// </summary>
public string LanguageCode
{
get { return _languageCode; }
set { _languageCode = value; OnPropertyChanged("LanguageCode"); }
}
/// <summary>
/// 语言名称 如:中国 ,English
/// </summary>
public string LanguageName
{
get { return _languageName; }
set { _languageName = value; OnPropertyChanged("LanguageName"); }
}
/// <summary>
/// 语言名称 如:中国 ,English
/// </summary>
public string LanguageDisplayName
{
get { return _languageDisplayName; }
set { _languageDisplayName = value; OnPropertyChanged("LanguageDisplayName"); }
} /// <summary>
/// 语言资源文件地址
/// </summary>
public string Resourcefile
{
get { return _resourcefile; }
set { _resourcefile = value; OnPropertyChanged("Resourcefile"); }
} /// <summary>
/// 是否启用此语言配置文件
/// </summary>
public bool LanguageEnabled
{
get { return _languageenabled; }
set { _languageenabled = value; OnPropertyChanged("LanguageEnabled"); }
} protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
} public event PropertyChangedEventHandler PropertyChanged;
}
}

核心类 I18N

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.IO; namespace WpfApplication1
{
public class Language : LanguageModel
{
private ResourceDictionary _resource; public ResourceDictionary Resource
{
get { return _resource; }
set { _resource = value; OnPropertyChanged("Resource"); }
}
} /// <summary>
/// 国际化 注:语言资源文件在VS2010的属性设置 复制到输出目录:始终复制 生成操作:内容
/// 资源文件 LanguageCode ,LanguageName, LanguageDisplayName,LanguageEnabled 字段必填
/// </summary>
public class I18N
{
private static string _currentLanguage = "zh-cn";
/// <summary>
/// 设置或获取语言编码,如果设置失败,则可能语言资源文件错误
/// </summary>
public static string CurrentLanguage
{
get { return _currentLanguage; }
set
{
if(UpdateCurrentLanguage(value))
_currentLanguage = value;
}
} private static List<Language> _languageIndex;
/// <summary>
/// 所有语言索引
/// </summary>
public static List<Language> LanguageIndex
{
get { return _languageIndex; }
} /// <summary>
/// 初始化,加载语言目录下的所有语言文件
/// </summary>
public static void Initialize()
{
_languageIndex = new List<Language>();
string dirstring = AppDomain.CurrentDomain.BaseDirectory + "Resource\\Language\\";
DirectoryInfo directory = new DirectoryInfo(dirstring);
FileInfo[] files = directory.GetFiles();
foreach (var item in files)
{
Language language = new Language();
ResourceDictionary rd = new ResourceDictionary();
rd.Source = new Uri(item.FullName);
language.LanguageCode = rd["LanguageCode"] == null ? "未知" : rd["LanguageCode"].ToString();
language.LanguageName = rd["LanguageName"] == null ? "未知" : rd["LanguageName"].ToString();
language.LanguageDisplayName = rd["LanguageDisplayName"] == null ? "未知" : rd["LanguageDisplayName"].ToString();
language.LanguageEnabled = rd["LanguageEnabled"] == null ? false : bool.Parse(rd["LanguageEnabled"].ToString());
language.Resourcefile = item.FullName;
language.Resource = rd;
if(language.LanguageEnabled)
_languageIndex.Add(language);
}
} /// <summary>
/// 更新语言配置. 同时同步CurrentLanguage字段
/// </summary>
private static bool UpdateCurrentLanguage(string LanguageCode)
{
if (LanguageIndex.Exists(P => P.LanguageCode == LanguageCode&&P.LanguageEnabled==true))
{
Language language = LanguageIndex.Find(P => P.LanguageCode == LanguageCode&&P.LanguageEnabled==true);
if (language != null)
{
foreach (var item in LanguageIndex)
{
Application.Current.Resources.MergedDictionaries.Remove(item.Resource);
}
Application.Current.Resources.MergedDictionaries.Add(language.Resource);
return true;
}
}
return false;
} /// <summary>
/// 查找语言资源文件具体的某项值,类似索引器
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetLanguageValue(string key)
{
ResourceDictionary rd = Application.Current.Resources;
if (rd == null)
return "";
object obj = rd[key];
return obj == null ? "" : obj.ToString();
} }
}

资料文件直接使用 XX.xaml文件    注:语言资源文件在VS2010的属性设置   复制到输出目录:始终复制     生成操作:内容   ,确保xaml文件会复制到项目中,而不是编译到dll中

 <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="LanguageCode">zh</sys:String>
<sys:String x:Key="LanguageName">简休中文</sys:String>
<sys:String x:Key="LanguageDisplayName">简休中文</sys:String>
<sys:String x:Key="LanguageEnabled">true</sys:String> <sys:String x:Key="LanguageLanguage">语言:</sys:String>
<sys:String x:Key="LanguageA">字段A:</sys:String>
<sys:String x:Key="LanguageB">字段B:</sys:String>
<sys:String x:Key="LanguageC">字段C:</sys:String> </ResourceDictionary>

默认语言可以在App.xaml里设置

 <Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="Application_Startup"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resource/Language/zh.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>

界面上使用动态绑定或静态绑定资源  (DynamicResource  ,StaticResource) ,  DataGrid表头使用HeaderSytle

动态绑定:可以实时更新语言种类.

  静态绑定,不能实时更新语言种类,如:在登录的时候已经确实语言种类,进入系统后而不能更改.

示例效果界面

 <Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="" Width="">
<Window.Resources>
<Style x:Key="HeaderA" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Content" Value="{DynamicResource LanguageA}" />
</Style>
<Style x:Key="HeaderB" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Content" Value="{DynamicResource LanguageB}" />
</Style>
<Style x:Key="HeaderC" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Content" Value="{DynamicResource LanguageC}" />
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40*" />
<RowDefinition Height="271*" />
</Grid.RowDefinitions>
<Label Content="{DynamicResource LanguageLanguage}" Height="" HorizontalAlignment="Left" Margin="26,12,0,0" Name="label1" VerticalAlignment="Top" />
<ComboBox Height="" HorizontalAlignment="Left" DisplayMemberPath="LanguageDisplayName" SelectedIndex="" Margin="160,12,0,0" Name="comboBox1" VerticalAlignment="Top" Width="" SelectionChanged="comboBox1_SelectionChanged" />
<DataGrid AutoGenerateColumns="False" Grid.Row="" Height="" HorizontalAlignment="Left" Margin="12,17,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="" >
<DataGrid.Columns>
<DataGridTemplateColumn Width="" HeaderStyle="{StaticResource HeaderA}" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="chkStart" IsChecked="{Binding IsStart,UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding Path=DataContext.IsEnabled, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Width="3*" HeaderStyle="{StaticResource HeaderB}" Binding="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="True" />
<DataGridTextColumn Width="3*" HeaderStyle="{StaticResource HeaderC}" Binding="{Binding Path=Website, UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors =True}" IsReadOnly="True" /> </DataGrid.Columns>
</DataGrid> </Grid>
</Window>

最后附上源代码  ,谢谢

End

技术在于分享,大家共同进步

WPF 实际国际化多语言界面的相关教程结束。

《WPF 实际国际化多语言界面.doc》

下载本文的Word格式文档,以方便收藏与打印。