EC-487 Added helper to localize enum values and also a converter to use in xaml (#2048)

This commit is contained in:
Federico Maccaroni 2022-08-23 12:34:29 -03:00 committed by GitHub
parent 9163b9e4de
commit d204e812e1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,33 @@
using System;
using System.Linq;
using System.Reflection;
using Bit.App.Resources;
using Bit.Core.Attributes;
using Xamarin.CommunityToolkit.Helpers;
namespace Bit.App.Utilities
{
public static class EnumHelper
{
public static string GetLocalizedValue<T>(T value)
{
return GetLocalizedValue(value, typeof(T));
}
public static string GetLocalizedValue(object value, Type type)
{
if (!type.GetTypeInfo().IsEnum)
{
throw new ArgumentException("type should be an enum");
}
var valueMemberInfo = type.GetMember(value.ToString())[0];
if (valueMemberInfo.GetCustomAttribute<LocalizableEnumAttribute>() is LocalizableEnumAttribute attr)
{
return AppResources.ResourceManager.GetString(attr.Key);
}
return value.ToString();
}
}
}

View File

@ -0,0 +1,23 @@
using System;
using Xamarin.Forms;
namespace Bit.App.Utilities
{
/// <summary>
/// It localizes an enum value by using the <see cref="Core.Attributes.LocalizableEnumAttribute"/>
/// </summary>
public class LocalizableEnumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return EnumHelper.GetLocalizedValue(value, value.GetType());
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
}

View File

@ -0,0 +1,14 @@
using System;
namespace Bit.Core.Attributes
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class LocalizableEnumAttribute : Attribute
{
public LocalizableEnumAttribute(string key)
{
Key = key;
}
public string Key { get; }
}
}

View File

@ -17,6 +17,7 @@
<None Remove="Resources\public_suffix_list.dat" />
<None Remove="Microsoft.AppCenter.Crashes" />
<None Remove="Services\Logging\" />
<None Remove="Attributes\" />
</ItemGroup>
<ItemGroup>
@ -35,5 +36,6 @@
<ItemGroup>
<Folder Include="Services\Logging\" />
<Folder Include="Attributes\" />
</ItemGroup>
</Project>