下载app免费领取会员
在WPF 用。net资源做多语言话的话,如果不要求动态切换可以在Xaml里直接使用Resource,在使用之前设置一下CultureInfo就可以了
如:
public MainWindow()
{
Res.Culture = CultureInfo.GetCultureInfo("en-US");
InitializeComponent();
}
如果要动态切换的话可以使用扩展标记:
public class LanguageUtils : MarkupExtension,INotifyPropertyChanged
{
private static ResourceManager manager = Res.ResourceManager;
private static EventHandler<EventArgs> LanguageChangeEvent;
public static void SetLanguage(string culture)
{
Res.Culture =new CultureInfo(culture);
if (LanguageChangeEvent != null)
LanguageChangeEvent(null, null);
}
static LanguageUtils()
{
// Res.Culture = new CultureInfo("en-US");
}
public LanguageUtils()
{
LanguageChangeEvent += LanguageChanged;
}
private void LanguageChanged(object sender, EventArgs e)
{
RaisePropertyChanged();
}
public string Key
{
get;
set;
}
public string Value
{
get
{
return manager.GetString(Key, Res.Culture);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged()
{
if(PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
IProvideValueTarget target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
FrameworkElement elm = target.TargetObject as FrameworkElement;
Binding binding = new Binding("Value")
{
Source = this,
Mode = BindingMode.OneWay
};
object obj = binding.ProvideValue(serviceProvider);
return obj;
}
}
在xaml里:
<Button Content="{local:LanguageUtils Key=String1}" HorizontalAlignment="Left" Margin="183,132,0,0" VerticalAlignment="Top" Width="212" Click="Button_Click"/>
切换事件:
private void Button_Click(object sender, RoutedEventArgs e)
{
if(Res.Culture.Name=="zh-CN")
LanguageUtils.SetLanguage("en-US");
else
LanguageUtils.SetLanguage("zh-CN");
}
本文版权归腿腿教学网及原创作者所有,未经授权,谢绝转载。
上一篇:二次开发教程:C#键盘钩子