WinUI3Localizer icon indicating copy to clipboard operation
WinUI3Localizer copied to clipboard

Recommended way to localize top-level UI components?

Open entrealist opened this issue 1 year ago • 2 comments

Is there are way to translate the top level UI component such a ContentDialog? What is recommended way to do this?

I wish to translate Title and PrimaryButtonText For instance like that:

<?xml version="1.0" encoding="utf-8" ?>
<ContentDialog
    x:Class="NotifyAloud.Views.AboutDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:l="using:WinUI3Localizer"
    xmlns:local="using:NotifyAloud"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="{l:Localize Key=AboutDialogTitle}" < 
    DefaultButton="Primary"
    PrimaryButtonText="{l:Localize Key=AboutDialogPrimaryButtonText}" <
    mc:Ignorable="d">

I've tried to use Bind also with the custom extension, not working either:

{
    [MarkupExtensionReturnType(ReturnType = typeof(string))]
    public class LocalizedStringExtension : MarkupExtension
    {
        public string Key { get; set; }

        protected override object ProvideValue()
        {
            var localizedString = Localizer.Get().GetLocalizedString(Key);
            return localizedString;
        }
    }
}

Appreciate your effort and time in making this awesome library.

entrealist avatar Sep 19 '24 23:09 entrealist

Hi @entrealist! In XAML, you can just assign the l:Uids.Uid:

<ContentDialog
    x:Class="NotifyAloud.Views.AboutDialog"
    xmlns:l="using:WinUI3Localizer"
    l:Uids.Uid="AboutDialog"... />

and have resources like:

<data name="AboutDialog.PrimaryButtonText" xml:space="preserve">
  <value>Yes</value>
</data>
<data name="AboutDialog.Title" xml:space="preserve">
  <value>This is the title.</value>
</data>

AndrewKeepCoding avatar Sep 20 '24 11:09 AndrewKeepCoding

or in C#, you can use the GetLocalizedString():

var localizer = WinUI3Localizer.Localizer.Get();
var dialog = new AboutDialog()
{
    XamlRoot = this.XamlRoot,
    Title = localizer.GetLocalizedString("AboutDialog_Title"),
    PrimaryButtonText = localizer.GetLocalizedString("AboutDialog_PrimaryButtonText"),
};
await dialog.ShowAsync();

AndrewKeepCoding avatar Sep 20 '24 12:09 AndrewKeepCoding

Feel free to reopen this if you have further questions about this.

AndrewKeepCoding avatar Nov 08 '24 04:11 AndrewKeepCoding