2
votes

Is it possible?:

//...
local:MvxBind="Text Format('{0} {1}', Stock, @string/in_stock)"/>
//...

I want to construct a text value using my property from ViewModel and string resource from strings.xml, but the example above does not work.

1

1 Answers

6
votes

AFAIK it is not directly possible to bind to an Android string.

Working with Xamarin and Mvx you should use resx files to support internationalization (i18n).

You can easily access the resx file from a binding using an indexer on your ViewModel:

public abstract class BaseViewModel : MvxViewModel
{
    public string this[string key] => Strings.ResourceManager.GetString(key);
}

Then in your View you can use it like:

local:MvxBind="Text Format('{0} {1}', Stock, [InStock])"


There is another way to bind strings in resx files that is using the ResxLocalization plugin and even though it does not support Format yet you can workaround it (you can check this issue Feature request: Combine MvxLang with Format to keep track of this)

Basically, you create your Strings.resx file in your PCL/NetStandard/Shared project and register it:

Mvx.RegisterSingleton(new MvxResxTextProvider(Strings.ResourceManager));

Then in your base view model you need to implement this property so your views and viewmodels have access to i18n:

public IMvxLanguageBinder TextSource => new MvxLanguageBinder("", GetType().Name);

Finally in your view you can call it using:

local:MvxLang="Text InStock"

Pay attention that it is using MvxLang instead of MvxBind. BTW you can use both of them but if you use Text in MvxLang then don't use it in MvxBind because problems will arise.

Finally you can combine the plugin with the indexer to lower the coupling between the ViewModel and the resx files and workaround the support of Format in the binding like this (taken from the issue abovementioned):

public abstract class BaseViewModel : MvxViewModel
{
    private IMvxTextProvider _textProvider;
    public BaseViewModel(IMvxTextProvider textProvider)
    {
        _textProvider = textProvider;
    }

    public string this[string key] => _textProvider.GetText("", "", key);
}

and in your view (because of Format we cannot use MvxLang here):

local:MvxBind="Text Format('{0} {1}', Stock, [InStock])"

HIH