MvvmCross Dynamic Text Value Conversion

≡放荡痞女 提交于 2020-01-13 17:06:14

问题


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'}}"
   />


来源:https://stackoverflow.com/questions/13471994/mvvmcross-dynamic-text-value-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!