简体   繁体   English

在 UWP 中的 XAML UI 中本地化字符串

[英]Localize strings in XAML UI in UWP

I have a resource entry named info_278 in the Resources.resw file on my UWP app.我的 UWP 应用程序的Resources.resw文件中有一个名为info_278的资源条目。 I have 3 scenarios where I need to use this resource but looks like I need to duplicate this to cater to different scenarios.我有 3 个场景需要使用此资源,但看起来我需要复制它以适应不同的场景。 Scenarios are as follows.场景如下。

  1. Error message content from code代码中的错误消息内容

    var displayErrorOnPopup = ResourceHandler.Get("info_278");

  2. TextBlock Text property from XAML (Looks like a new entry needed as info_278.Text )来自 XAML 的 TextBlock Text 属性(看起来像info_278.Text需要的新条目)

    <TextBlock x:Uid="info_278" Margin="10,0,0,0" />

  3. Button Content property from XAML (Looks like a new entry needed as info_278.Content ) XAML 的按钮内容属性(看起来像info_278.Content需要的新条目)

    <Button x:Uid="info_278" Margin="10,0,0,0" />

How do I proceed without duplicating this resource in the .resw file?如何在不复制.resw文件中的资源的情况下继续操作?


在此处输入图像描述

The only way to avoid duplication is to set the string value in code-behind using ResourceLoader .避免重复的唯一方法是使用ResourceLoader在代码隐藏中设置字符串值。 Because you could direct access to the specific property of the target control.因为您可以直接访问目标控件的特定属性。 Like this:像这样:

var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
this.TextBlock.Text = resourceLoader.GetString("info_278");

If you are not going to do it in the code behind, then I have to say there is no way to avoid the duplication of the resource string.如果不打算在后面的代码中进行,那我不得不说没有办法避免资源字符串的重复。 You should add info_278.Text and info_278.Content for different XAML scenarios.您应该为不同的 XAML 方案添加info_278.Textinfo_278.Content

You could create a markup extension.您可以创建一个标记扩展。 I've used this in WinUI 3, but should work in UWP too.我在 WinUI 3 中使用过它,但也应该在 UWP 中工作。

using Microsoft.UI.Xaml.Markup;
using Windows.ApplicationModel.Resources;

namespace MyApp;

[MarkupExtensionReturnType(ReturnType = typeof(string))]
public class StringResourceExtension : MarkupExtension
{
    private static readonly ResourceLoader _resourceLoader = new();

    public StringResourceExtension() { }

    public string Key { get; set; } = "";

    protected override object ProvideValue()
    {
        return _resourceLoader.GetString(Key);
    }
}

Then in the XAML:然后在 XAML 中:

...
local="using:MyApp"
...

<TextBlock Text="{local:StringResource Key=info_278}" />
<Button Content="{local:StringResource Key=info_278}" />

The Content of Button can be a TextBlock : ButtonContent可以是TextBlock

<Button>
  <TextBlock x:Uid="MyTextId" Style="{StaticResource MyTextBlockStyle}" />
</Button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM