How to binding general string indexers?
I have a general language change singleton class
public class LanguageManager : INotifyPropertyChanged { private readonly ResourceManager _resourceManager; private static readonly Lazy<LanguageManager> Lazy = new(() => new LanguageManager()); public static LanguageManager Instance => Lazy.Value;
private LanguageManager()
{
_resourceManager = new ResourceManager(typeof(Resource));
}
public string this[string name]
{
get
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return _resourceManager.GetString(name)!;
}
}
public void ChangeLanguage(string languageName)
{
var culture = CultureInfo.GetCultureInfo(languageName);
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
}
public event PropertyChangedEventHandler? PropertyChanged;
}
In WPF you can do this:
<TextBlockText="{Binding [Welcome], Source={x:Static localization:LanguageManager.Instance}}" />
But this cannot be done in WinUI3:
<TextBlock Text="{Binding [Welcome], Source={x:Static localization:LanguageManager.Instance}}" />
- No x:static
- Binding needs to contain a public constructor
- Can not work If I switch to x:bind: <TextBlock Text="{x:Bind localization:LanguageManager.Instance['Welcome'], Mode=OneWay}" />
- Is this question related to mine?[(#3064)]
So, In winui3, How to do?
Maybe Markup Extensions fit your needs: https://devblogs.microsoft.com/ifdef-windows/use-a-custom-resource-markup-extension-to-succeed-at-ui-string-globalization/
也许标记扩展可以满足您的需求:https://devblogs.microsoft.com/ifdef-windows/use-a-custom-resource-markup-extension-to-succeed-at-ui-string-globalization/
This article does not seem to implement the code for dynamically switching languages
Never tried it, but in theory it looks like it should also work in WinUI 3: https://thomaslevesque.com/2009/07/28/wpf-a-markup-extension-that-can-update-its-target/ https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.markup.markupextension.providevalue?view=windows-app-sdk-1.5#microsoft-ui-xaml-markup-markupextension-providevalue(microsoft-ui-xaml-ixamlserviceprovider) https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.markup.iprovidevaluetarget?view=windows-app-sdk-1.5
@RedTellYou Not an answer for you question but if you want to dynamically switch languages, try the WinUI3Localizer (Diclosure: I'm the author.).
@whiskhub @AndrewKeepCoding My project requires WPF and WinUI3 to share MVVM, so I can only consider how to achieve multi-language compatibility. The methods you provide can only be used in WinUI3, not in WPF.