MvvmCross: Android 布局绑定字符串资源

MvvmCross: Android layout binding string resource

可以吗?:

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

我想使用来自 ViewModel 的 属性 和来自 strings.xml 的字符串资源构建文本值,但上面的示例不起作用。

据我所知,无法直接绑定到 Android 字符串。

使用 Xamarin 和 Mvx,您应该使用 resx 文件来支持国际化 (i18n)。

您可以使用 ViewModel 上的索引器从绑定轻松访问 resx 文件:

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

然后在您的视图中,您可以像这样使用它:

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


还有另一种在 resx 文件中绑定字符串的方法,它使用 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 来跟踪这个)

基本上,您在 PCL/NetStandard/Shared 项目中创建 Strings.resx 文件并注册它:

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

然后在你的基础视图模型中你需要实现这个 属性 这样你的视图和视图模型就可以访问 i18n:

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

最后在您看来,您可以使用以下方式调用它:

local:MvxLang="Text InStock"

注意这里使用的是MvxLang而不是MvxBind。顺便说一句,你可以同时使用它们,但是如果你在 MvxLang 中使用 Text,那么不要在 MvxBind 中使用它,因为会出现问题。

最后,您可以将插件与索引器结合使用,以降低 ViewModel 和 resx 文件之间的耦合,并解决绑定中对 Format 的支持(取自上述问题) ):

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

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

并且在您看来(因为 Format 我们不能在这里使用 MvxLang):

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