【发布时间】:2017-10-18 11:54:50
【问题描述】:
使用 MvvmCross,我创建了一种跨平台方法来翻译 Android 和 iOS 上的字符串,因此我可以在我的 ViewModel 中使用一个共享的 translate() 方法。我在我的核心项目中有一个共享接口ILocalizationHelper,在每个平台中我都创建了一个从接口继承的LocalizationHelper 类。所以我的ViewModel 现在包含一个ILocalizationHelper 实例,我可以在该实例上使用我的translate() 方法。
问题:要在Android 上使用GetString() 翻译字符串,我需要一个上下文(Activity)。所以实例化这个LocalizationHelper 并不简单。目前我使用MvxViewModel 中的Translator 属性解决了这个问题,我可以从我的视图中设置。
我的Fragment类如下:
[MvxFragment(typeof(AccountViewModel), Resource.Id.content_frame, AddToBackStack = true)]
[Register("appname.Android.Fragments.Account.LoginFragment")]
public class LoginFragment : MvxFragment<LoginViewModel>
{
base.OnCreateView(inflater, container, savedInstanceState);
View view = this.BindingInflate(Resource.Layout.FragmentLogin, container, false);
ViewModel.Translator = new LocalizationHelper(Activity);
}
现在我在想这可能是不好的做法(是吗?)。所以我更喜欢使用 ViewModel 的构造函数注入我的 LocalizationHelper 实例。但我不知道我怎么能做到这一点,如果它甚至可能的话:
private ILocalizationHelper _translator;
public ILocalizationHelper Translator
{
get { return _translator; }
set { _translator = value; }
}
public LoginViewModel(ILocalizationHelper localizationHelper)
{
_translator = localizationHelper;
}
感谢您对与此相关的最佳实践的任何启发。
【问题讨论】:
标签: c# android xamarin mvvm mvvmcross