Use strings in .resw File directly in XAML

前端 未结 2 1020
逝去的感伤
逝去的感伤 2021-01-22 08:07

I know the usual way to reference localized strings from a .resw file would be like this:

XAML:

Re

2条回答
  •  一向
    一向 (楼主)
    2021-01-22 08:23

    I once did something similar, where we added any new strings to the Android string resource file, then used custom build tools convert those into iOS and Windows formats.

    An Android string might look like this:

    Hello, World!
    

    Our tool converts this into a Windows string resource:

    
      Hello, World!
    
    

    Next, add a converter that does nothing to the provided value, but instead assumes its parameter is a resource id:

    public sealed class LocalizeConverter : IValueConverter
    {
        private static readonly ResourceLoader Loader = ResourceLoader.GetForViewIndependentUse("/Resources");
    
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            string resourceId = parameter as string;
            return !string.IsNullOrEmpty(resourceId) ? Loader.GetString(resourceId) : DependencyProperty.UnsetValue;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotSupportedException();
        }
    }
    

    Now make that converter available to your XAML, perhaps something like this:

    
        
    
    

    And finally, set your Button's Content property as follows:

    Note that we don't supply any value to the converter. (In WPF I would have created a markup extension. Sadly, this option is not available in UWP, so I came up with this value-less converter option as an alternative.)

    If you want to get even niftier, consider this:

    This lets you change the language on the fly, if you have resources localized into other languages. (Note Mode=OneWay instead of Mode=OneTime.)

提交回复
热议问题