MvvmCross Dynamic Text Value Conversion

2019-05-14 01:56发布

问题:

As far as I know, MvvmCross localization plugin provides "static" engine. I use the following binding as an example from Conference:

local:MvxBind="{'Text'{'Path':'TextSource','Converter':'Language','ConverterParameter':'SQLBitsXApp'}}"

I want to be able to change SQLBitsXApp to SQLBitsXApp2 dynamically. The goal is to find the localized text related to days enum.

Is there a way to do this dynamically ?

回答1:

You're correct - the default MvxLanguageConverter used in that binding is really there only for simple static text.

For more involved situations you will need to build your own converter for each case - but hopefully some of these will be reusable.

As a starting example, check out how the Conference sample displays tweet times using TimeAgoConverter.cs

public class TimeAgoValueConverter
    : MvxBaseValueConverter
      , IMvxServiceConsumer<IMvxTextProvider>
{
    private IMvxTextProvider _textProvider;
    private IMvxTextProvider TextProvider
    {
        get
        {
            if (_textProvider == null)
            {
                _textProvider = this.GetService<IMvxTextProvider>();
            }
            return _textProvider;
        }
    }

    public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var when = (DateTime)value;

        string whichFormat;
        int valueToFormat;

        if (when == DateTime.MinValue)
        {
            whichFormat = "TimeAgo.Never";
            valueToFormat = 0;
        }
        else
        {
            var whenUtc = when.ToUniversalTime();
            var difference = (DateTime.UtcNow - whenUtc).TotalSeconds;
            if (difference < 30.0)
            {
                whichFormat = "TimeAgo.JustNow";
               valueToFormat = 0;
            }
            // ... etc
        }

        var format = TextProvider.GetText(Constants.GeneralNamespace, Constants.Shared, whichFormat);
        return string.Format(format, valueToFormat);
    }
}

This is used in Android axml like in https://github.com/slodge/MvvmCross/blob/vnext/Sample%20-%20CirriousConference/Cirrious.Conference.UI.Droid/Resources/Layout/ListItem_Tweet.xml:

<TextView
 android:id="@+id/TimeTextView"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textSize="10dip"
 android:textColor="@color/icongrey"
  local:MvxBind="{'Text':{'Path':'Item.Timestamp','Converter':'TimeAgo'}}"
   />