使用.NET MAUI picker中的本地化

huangapple go评论97阅读模式
英文:

Using localization in .NET MAUI picker

问题

<Picker Title="{x:Static resx:AppResources.PickerTitle}">
    <Picker.ItemsSource>
        <x:Array Type="{x:Type x:String}">
            <x:String>{x:Static resx:AppResources.Option1}</x:String>
            <x:String>{x:Static resx:AppResources.Option2}</x:String>
            <x:String>{x:Static resx:AppResources.Option3}</x:String>
        </x:Array>
    </Picker.ItemsSource>
</Picker>
英文:

`I created resx files in my .NET MAUI project to use different languages. I want to use them within a picker. I followed the approach below in XAML, but it didn't work. What should I do?

&lt;Picker Title=&quot;{x:Static resx:AppResources.PickerTitle}&quot;&gt;
    &lt;Picker.ItemsSource&gt;
        &lt;x:Array Type=&quot;{x:Type x:String}&quot;&gt;
            &lt;x:String&gt;{x:Static resx:AppResources.Option1}&lt;/x:String&gt;
            &lt;x:String&gt;{x:Static resx:AppResources.Option2}&lt;/x:String&gt;
            &lt;x:String&gt;{x:Static resx:AppResources.Option3}&lt;/x:String&gt;
        &lt;/x:Array&gt;
    &lt;/Picker.ItemsSource&gt;
&lt;/Picker&gt;

`

答案1

得分: 0

以下是翻译好的部分:

这是一个使用两种语言(英语、德语)的示例,其中英语是默认语言:

<!-- MainPage.xaml -->
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:resources="clr-namespace:YourAppName.Resources"
             x:Class="YourAppName.MainPage">

    <StackLayout Padding="20">
        <Label Text="{x:Static resources:AppResources.Title}" FontSize="24" />
        <Picker x:Name="languagePicker" Title="Select Language" SelectedIndexChanged="OnLanguagePickerIndexChanged">
            <Picker.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>English</x:String>
                    <x:String>German</x:String>
                </x:Array>
            </Picker.ItemsSource>
        </Picker>
    </StackLayout>

</ContentPage>
using System;
using System.Globalization;
using Microsoft.Maui.Controls;

namespace YourAppName
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void OnLanguagePickerIndexChanged(object sender, EventArgs e)
        {
            var selectedLanguage = languagePicker.SelectedItem as string;

            if (selectedLanguage == "English")
            {
                SetLanguage("en");
            }
            else if (selectedLanguage == "German")
            {
                SetLanguage("de");
            }
        }

        private void SetLanguage(string languageCode)
        {
            CultureInfo newCulture = new CultureInfo(languageCode);
            CultureInfo.DefaultThreadCurrentCulture = newCulture;
            CultureInfo.DefaultThreadCurrentUICulture = newCulture;

            // 刷新当前页面以更新本地化字符串
            Application.Current.MainPage = new MainPage();
        }
    }
}

为每种语言创建资源文件。例如:

  • AppResources.resx(默认 - 英语)
  • AppResources.de.resx(德语)

打开每个资源文件,并为每种语言的相同名称但不同值的本地化字符串添加条目。例如,对于 "Title" 键:

AppResources.resx(默认 - 英语):

Key: Title, Value: My App

AppResources.de.resx(德语):

Key: Title, Value: Meine App

英文:

Here is an example how to do it with two languages (English, German) where English is the default language:

<!-- MainPage.xaml -->
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:resources="clr-namespace:YourAppName.Resources"
x:Class="YourAppName.MainPage">

&lt;StackLayout Padding=&quot;20&quot;&gt;
    &lt;Label Text=&quot;{x:Static resources:AppResources.Title}&quot; FontSize=&quot;24&quot; /&gt;
    &lt;Picker x:Name=&quot;languagePicker&quot; Title=&quot;Select Language&quot; SelectedIndexChanged=&quot;OnLanguagePickerIndexChanged&quot;&gt;
        &lt;Picker.ItemsSource&gt;
            &lt;x:Array Type=&quot;{x:Type x:String}&quot;&gt;
                &lt;x:String&gt;English&lt;/x:String&gt;
                &lt;x:String&gt;German&lt;/x:String&gt;
            &lt;/x:Array&gt;
        &lt;/Picker.ItemsSource&gt;
    &lt;/Picker&gt;
&lt;/StackLayout&gt;

</ContentPage>

using System;
using System.Globalization;
using Microsoft.Maui.Controls;

namespace YourAppName
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void OnLanguagePickerIndexChanged(object sender, EventArgs e)
        {
            var selectedLanguage = languagePicker.SelectedItem as string;

            if (selectedLanguage == &quot;English&quot;)
            {
                SetLanguage(&quot;en&quot;);
            }
            else if (selectedLanguage == &quot;German&quot;)
            {
                SetLanguage(&quot;de&quot;);
            }
        }

        private void SetLanguage(string languageCode)
        {
            CultureInfo newCulture = new CultureInfo(languageCode);
            CultureInfo.DefaultThreadCurrentCulture = newCulture;
            CultureInfo.DefaultThreadCurrentUICulture = newCulture;

            // Refresh the current page to update the localized strings
            Application.Current.MainPage = new MainPage();
        }
    }
}

Create resource files for each language. For example:

  • AppResources.resx (Default - English)
  • AppResources.de.resx (German)

Open each resource file and add localized strings with the same names but different values for each language. For example, for the "Title" key:

AppResources.resx (Default - English):

Key: Title, Value: My App

AppResources.de.resx (German):

Key: Title, Value: Meine App

答案2

得分: 0

以下是翻译好的内容:

这是一个使用BehavioursWeakReferenceMessenger的可能解决方案。虽然不是非常漂亮,但具有潜力。

要求是您已经创建了您想要的不同语言的资源。

让我们从实现开始。我们有一个选择器和一个单选按钮组。选择器具有一个行为,将执行所有的魔法。

<Picker x:Name="MyPicker" Title="{x:Static localization:AppResources.PickerTitle}">
   <Picker.Behaviors>
      <local:LocalizedPickerBehavior />
   </Picker.Behaviors>
</Picker>
<local:RadioButtonGroup />

我们创建了这个行为。在这里,我们初始化了Messenger,它将告诉行为我们已经更改了语言。

public class LocalizedPickerBehavior : Behavior<Picker>
{
    protected override void OnAttachedTo(Picker picker)
    {
        base.OnAttachedTo(picker);

        // 设置Picker的ItemsSource
        SetItemsSource(picker);

        // 监听LanguageChanged通知
        WeakReferenceMessenger.Default.Register<LocalizedPickerBehaviorMessage>(this, (recipient, message) =>
        {
            var culture = new CultureInfo(message.Value);
            CultureInfo.CurrentUICulture = culture;
            SetItemsSource(picker);
        });
    }

    private void SetItemsSource(Picker picker)
    {
        var option1 = AppResources.Option1;
        var option2 = AppResources.Option2;
        var option3 = AppResources.Option3;

        picker.Title = AppResources.PickerTitle;
        var currentIndex = picker.SelectedIndex;
        picker.ItemsSource = new List<string> { option1, option2, option3 };
        picker.SelectedIndex = currentIndex;
    }

    protected override void OnDetachingFrom(Picker picker)
    {
        base.OnDetachingFrom(picker);

        picker.ItemsSource = null;

        WeakReferenceMessenger.Default.Unregister<LocalizedPickerBehavior>(this);
    }
}

对于Messenger,我们需要发送带有我们要切换到的语言的消息。

public class LocalizedPickerBehaviorMessage : ValueChangedMessage<string>
{
    public LocalizedPickerBehaviorMessage(string lang) : base(lang)
    {
    }
}

最后,我们使用一个简单的单选按钮,将消息发送到我们的行为。

public class RadioButtonGroup : StackLayout
{
    public RadioButton RadioButton1 { get; private set; }
    public RadioButton RadioButton2 { get; private set; }

    public RadioButtonGroup()
    {
        Orientation = StackOrientation.Horizontal;
        RadioButton1 = new RadioButton { Content = "English" };
        RadioButton2 = new RadioButton { Content = "Swedish" };

        RadioButton1.CheckedChanged += OnRadioButtonCheckedChanged;
        RadioButton2.CheckedChanged += OnRadioButtonCheckedChanged;

        Children.Add(RadioButton1);
        Children.Add(RadioButton2);

        RadioButton1.IsChecked = true;
    }

    private void OnRadioButtonCheckedChanged(object sender, CheckedChangedEventArgs e)
    {
        var radioButton = (RadioButton)sender;

        if (radioButton == RadioButton1 && RadioButton1.IsChecked)
        {
            RadioButton2.IsChecked = false;
            WeakReferenceMessenger.Default.Send(new LocalizedPickerBehaviorMessage("en"));
        }
        else if (radioButton == RadioButton2 && RadioButton2.IsChecked)
        {
            RadioButton1.IsChecked = false;
            WeakReferenceMessenger.Default.Send(new LocalizedPickerBehaviorMessage("sv"));
        }
    }
}

这是一个可视化示例:

使用.NET MAUI picker中的本地化

英文:

Her is a possible solution that uses Behaviours and WeakReferenceMessenger. Not all that pretty but has possibilities.

Requirement is that you have made the resources for the different language you want.

Let us start with the implementation. We got a picker and a radio buttons group. The picker got a Behavior that is going to do all the magic.

&lt;Picker x:Name=&quot;MyPicker&quot; Title=&quot;{x:Static localization:AppResources.PickerTitle}&quot;&gt;
   &lt;Picker.Behaviors&gt;
      &lt;local:LocalizedPickerBehavior /&gt;
   &lt;/Picker.Behaviors&gt;
&lt;/Picker&gt;
&lt;local:RadioButtonGroup /&gt;

We create the behaviour. Here we initialize the Messenger that will tell the Behaviour that we have changed language.

public class LocalizedPickerBehavior : Behavior&lt;Picker&gt;
{
    protected override void OnAttachedTo(Picker picker)
    {
        base.OnAttachedTo(picker);

        // Set the ItemsSource of the Picker
        SetItemsSource(picker);


        // Listen for the LanguageChanged notification
        WeakReferenceMessenger.Default.Register&lt;LocalizedPickerBehaviorMessage&gt;(this, (recipient, message) =&gt; {
            var culture = new CultureInfo(message.Value);
            CultureInfo.CurrentUICulture = culture;
            SetItemsSource(picker);
        });
    }

    private void SetItemsSource(Picker picker)
    {
        var option1 = AppResources.Option1;
        var option2 = AppResources.Option2;
        var option3 = AppResources.Option3;

        picker.Title = AppResources.PickerTitle;
        var currentIndex = picker.SelectedIndex;
        picker.ItemsSource = new List&lt;string&gt; { option1, option2, option3 };
        picker.SelectedIndex = currentIndex;
    }

    protected override void OnDetachingFrom(Picker picker)
    {
        base.OnDetachingFrom(picker);

        picker.ItemsSource = null;

        WeakReferenceMessenger.Default.Unregister&lt;LocalizedPickerBehavior&gt;(this);
    }
}

For the messenger we need a message that we send with the language we want to change to.

public class LocalizedPickerBehaviorMessage : ValueChangedMessage&lt;string&gt;
{
    public LocalizedPickerBehaviorMessage(string lang) : base(lang)
    {
    }
}

And we finnish of with a simple radio button that sends the message to our behaviour.

public class RadioButtonGroup : StackLayout
{
    public RadioButton RadioButton1 { get; private set; }
    public RadioButton RadioButton2 { get; private set; }

    public RadioButtonGroup()
    {
        Orientation = StackOrientation.Horizontal;
        RadioButton1 = new RadioButton { Content = &quot;English&quot; };
        RadioButton2 = new RadioButton { Content = &quot;Swedish&quot; };

        RadioButton1.CheckedChanged += OnRadioButtonCheckedChanged;
        RadioButton2.CheckedChanged += OnRadioButtonCheckedChanged;

        Children.Add(RadioButton1);
        Children.Add(RadioButton2);

        RadioButton1.IsChecked = true;
    }

    private void OnRadioButtonCheckedChanged(object sender, CheckedChangedEventArgs e)
    {
        var radioButton = (RadioButton)sender;

        if (radioButton == RadioButton1 &amp;&amp; RadioButton1.IsChecked)
        {
            RadioButton2.IsChecked = false;
            WeakReferenceMessenger.Default.Send(new LocalizedPickerBehaviorMessage(&quot;en&quot;));
        }
        else if (radioButton == RadioButton2 &amp;&amp; RadioButton2.IsChecked)
        {
            RadioButton1.IsChecked = false;
            WeakReferenceMessenger.Default.Send(new LocalizedPickerBehaviorMessage(&quot;sv&quot;));
        }
    }
}

Here is a visual:

使用.NET MAUI picker中的本地化

huangapple
  • 本文由 发表于 2023年7月31日 20:33:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76803673.html
  • c#
  • maui
  • xaml

为所有缺失的枚举添加到List中。 go 66
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定

  • 开发者交流平台

    本页二维码