Локализация среды выполнения для приложения .NET WPFC#

Место общения программистов C#
Ответить
Anonymous
 Локализация среды выполнения для приложения .NET WPF

Сообщение Anonymous »

Я работаю над локализацией старого программного обеспечения, написанного на C#. Это приложение .NET WPF, которое использует два окна XAML для графического интерфейса. Я создал класс LocalizationManager для обработки переводов, а строки хранятся в двух файлах .resx (для английского и немецкого языков).
Переводы работают правильно — я могу изменить язык в настройках, а выбранный язык сохраняется в файле settings.xml, поэтому он сохраняется при перезапуске приложения.
Теперь мне нужно реализовать переключение языка во время выполнения. Я хочу, чтобы изменение языка вступило в силу немедленно, без перезапуска приложения.
Я не являюсь опытным разработчиком программного обеспечения, поэтому ищу простое решение или лучшие практики для этой задачи. Как мне перезагрузить окна или вызвать необходимые события для обновления пользовательского интерфейса на новом языке?
Заранее спасибо за помощь!
мой Класс LocalizationManager.cs:

Код: Выделить всё

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Threading;

namespace ProgrammierstationV2.Logic.Localization
{
/// 
/// A class for managing the localisation of texts based on resource files.
/// 

class LocalizationManager
{
private ResourceManager _resourceManager;
// Property for defining and retrieving the current culture for localisation purposes
public CultureInfo CurrentCulture { get; set; }
static private bool eninitialized = false;
static private CultureInfo cinfo;

private static readonly Lazy _instance = new Lazy(() => new LocalizationManager());

/// 
/// The singleton instance of LocalizationManager.
/// 
public static LocalizationManager Instance => _instance.Value;

/// 
/// Event that is triggered when the language is changed.
/// 
public event EventHandler LanguageChanged;

/// 
/// Private constructor to prevent instantiation.
/// Initialises the resource manager instance based on the name of the resource file and the assembly type.
/// 
private LocalizationManager()
{
// Initialisation of the resource manager with the name of the resource file
// and the assembly type of the LocalisationManager class>
_resourceManager = new ResourceManager("ProgrammierstationV2.LocalizationResources.Strings", typeof(LocalizationManager).Assembly);

// Sets the default language to English
if (eninitialized == true)
{
CurrentCulture = cinfo;
}
else
{
cinfo = new CultureInfo("en-GB");
eninitialized = true;
CurrentCulture = cinfo;
}
}

/// 
/// Returns a list of supported languages.
/// 
/// A list of supported languages as culture codes.
public List GetSupportedLanguages()
{
return new List { "en-GB", "de-DE"  };
}

/// 
/// Displays the localised text for a specific key.
/// 
/// 
The key that references the desired localised text in the resource file.
public string DisplayLocalizedText(string key)
{
SetCulture(CurrentCulture);

// Retrieve the localised text for the specified key
string localizedText = _resourceManager.GetString(key);

// Check whether the resource has been found
if (localizedText == null)
{
// Generate an error message that the resource is missing
Console.WriteLine($"Error: Resource with key '{key}' is missing in resource files.");
// Returns a standard text or null
return "Error: Missing Resource";
}

// Retrieve and return the localised text for the specified key
return localizedText;
}

/// 
/// Sets the current culture for localisation.
/// 
/// The desired culture.
public void SetCulture(CultureInfo culture)
{
// Setting the current culture and UI culture
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}

/// 
/// Changes the current language for localisation.
/// 
/// The culture code of the desired language.
public void ChangeLanguage(string languageCode)
{
// Check whether the specified language is supported
if (GetSupportedLanguages().Contains(languageCode))
{
// Create a new CultureInfo instance with the specified language code
CultureInfo newCulture = new CultureInfo(languageCode);
cinfo = newCulture;

// Set the current culture for localisation
SetCulture(newCulture);

// Updating the CurrentCulture property
CurrentCulture = newCulture;
}
}
}
}
Коллега предложил мне использовать обработчики событий в файле MainViewModel.cs (файл, в который файл settings.xml загружается при запуске приложения). Однако мне не удалось добиться большого прогресса с помощью этого подхода. Другой предлагал многопоточность, но сейчас у меня не было времени разбираться в этом. Я также открыт для разных подходов.


Подробнее здесь: https://stackoverflow.com/questions/789 ... pplication
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»