You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
2.7 KiB
90 lines
2.7 KiB
using System;
|
|
using System.Globalization;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace MyAvaloniaApp.Services
|
|
{
|
|
/// <summary>
|
|
/// 语言管理器,用于管理应用程序的语言设置
|
|
/// </summary>
|
|
public class LanguageManager
|
|
{
|
|
private readonly IResourceService _resourceService;
|
|
private CultureInfo _currentCulture;
|
|
|
|
public event EventHandler<CultureInfo>? LanguageChanged;
|
|
|
|
public LanguageManager(IResourceService resourceService)
|
|
{
|
|
_resourceService = resourceService;
|
|
_currentCulture = CultureInfo.CurrentCulture;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取当前语言
|
|
/// </summary>
|
|
public CultureInfo CurrentCulture => _currentCulture;
|
|
|
|
/// <summary>
|
|
/// 获取当前语言名称
|
|
/// </summary>
|
|
public string CurrentLanguageName => _currentCulture.Name.StartsWith("zh") ? "中文" : "English";
|
|
|
|
/// <summary>
|
|
/// 切换语言
|
|
/// </summary>
|
|
/// <param name="culture">目标语言文化信息</param>
|
|
public async Task SwitchLanguageAsync(CultureInfo culture)
|
|
{
|
|
if (_currentCulture != culture)
|
|
{
|
|
_currentCulture = culture;
|
|
_resourceService.SetCulture(culture);
|
|
|
|
// 触发语言变更事件
|
|
LanguageChanged?.Invoke(this, culture);
|
|
|
|
// 这里可以添加其他语言切换逻辑,比如重新加载UI等
|
|
await OnLanguageChangedAsync(culture);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 切换到中文
|
|
/// </summary>
|
|
public async Task SwitchToChineseAsync()
|
|
{
|
|
await SwitchLanguageAsync(new CultureInfo("zh-CN"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// 切换到英文
|
|
/// </summary>
|
|
public async Task SwitchToEnglishAsync()
|
|
{
|
|
await SwitchLanguageAsync(new CultureInfo("en-US"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// 切换语言(中文/英文)
|
|
/// </summary>
|
|
public async Task ToggleLanguageAsync()
|
|
{
|
|
if (_currentCulture.Name.StartsWith("zh"))
|
|
{
|
|
await SwitchToEnglishAsync();
|
|
}
|
|
else
|
|
{
|
|
await SwitchToChineseAsync();
|
|
}
|
|
}
|
|
|
|
private async Task OnLanguageChangedAsync(CultureInfo culture)
|
|
{
|
|
// 这里可以添加语言切换后的处理逻辑
|
|
// 比如重新加载页面内容、更新UI等
|
|
await Task.CompletedTask;
|
|
}
|
|
}
|
|
}
|
|
|