微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Xamarin Forms本地化在运行时映像未在iOS中更新

如何解决Xamarin Forms本地化在运行时映像未在iOS中更新

我有一个带有语言选择器的Xamarin Forms应用程序,它将向客户公开。 切换语言时,我调用SetLocale()方法来切换当前语言。

public static void SetLocale(CultureInfo culture)
{
    Thread.CurrentThread.CurrentCulture = culture;
    Thread.CurrentThread.CurrentUICulture = culture;
    AppResources.Culture = culture;  
}

所有文本都进行了很好的更新(它们来自resx文件),但是图像仍然是我在info.plist中定义的认应用程序语言(在应用程序设置中选择)的一种。

enter image description here

我按照xamarin文档将图像放在Resources / .lproj中的iOS项目中

enter image description here

我通常将它们绑定到xaml文件

<Image Source="{Binding Image}"></Image>

如何使图像也能翻译?

解决方法

经过大量研究,我找不到使用本机iOS捆绑包的方法。

最后,我在this tutorial之后进行了标记扩展,并对其进行了自定义,以在图像不存在时回退到默认语言环境。

using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
    
namespace XamarinTest.Custom
{
    [ContentProperty(nameof(Source))]
    public class ImageResourceExtension : IMarkupExtension
    {
        public string Source { get; set; }
    
        public object ProvideValue(IServiceProvider serviceProvider)
        {
           if (Source == null)
               return null;
           var resourceName = string.Format("XamarinTest.Images.{0}.{1}",CultureInfo.CurrentUICulture.Name.Replace('-','_'),Source);
           if (ResourceExists(resourceName))
               return ImageSource.FromResource(resourceName,typeof(ImageResourceExtension).GetTypeInfo().Assembly);
           return ImageSource.FromResource(string.Format("XamarinTest.Images.default.{0}",Source),typeof(ImageResourceExtension).GetTypeInfo().Assembly);
        }
    
        private string[] resourceNames;
    
        private bool ResourceExists(string resourceName)
        {
            if (resourceNames == null)
            {
                resourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames();
            }
            return resourceNames.Contains(resourceName);
        }
    }
}

我将每个图像的构建操作设置为EmbeddedResource

project structure

然后在视图中,我只添加

xmlns:l="clr-namespace:XamarinTest.Custom"
...
<Image Source="{l:ImageResource qr.png}"
   HeightRequest="160"
   WidthRequest="160"></Image>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。