1
正如標題所寫,我有我的MvvmLight應用程序下Xamarin.Forms問題。 我有這樣的代碼爲我的示例ViewModel。如何在LightMvvm中使用構造函數注入註冊ViewModel Xamarin.Forms?
public interface IMainViewModel
{
}
public class MainViewModel : ViewModelBase, IMainViewModel
{
private readonly IDataService<Todoo> _dataService;
private readonly INavigationService _navigationService;
public MainViewModel(IDataService<Todoo> dataService, INavigationService navigationService)
{
if (navigationService == null)
throw new ArgumentNullException(nameof(navigationService), "Navigation service cannot be null");
_navigationService = navigationService;
if (dataService == null)
throw new ArgumentNullException(nameof(dataService), "Data service cannot be null");
_dataService = dataService;
NavigationCommand = new RelayCommand<string>(parameter => Navigate(parameter));
}
private void Navigate(string parameter)
{
// _navigationService.NavigateTo(ViewModelLocator.MainPage, parameter ?? string.Empty);
_navigationService.NavigateTo(ViewModelLocator.AddNewTodooPage);
}
public RelayCommand<string> NavigationCommand { get; private set; }
}
這是一個ViewModelLocator
public class ViewModelLocator
{
public const string MainPage = "MainPage";
public const string AddNewTodooPage = "AddNewTodooPage";
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<IMainViewModel, MainViewModel>();
SimpleIoc.Default.Register<IAddNewTodooViewModel, AddNewTodooViewModel>();
}
public MainViewModel Main => ServiceLocator.Current.GetInstance<MainViewModel>();
public AddNewTodooViewModel AddNewTodoo => ServiceLocator.Current.GetInstance<AddNewTodooViewModel>();
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
而且App.cs
public partial class App
{
private static ViewModelLocator _locator;
public static ViewModelLocator Locator => _locator ?? (_locator = new ViewModelLocator());
public App()
{
SimpleIoc.Default.Register<IDataService<Todoo>>(() => new TodoosDataService());
SimpleIoc.Default.Register<IRepository<Todoo>>(() => new FakeTodoosRepository());
var nav = new NavigationService();
nav.Configure(ViewModelLocator.MainPage, typeof(MainPage));
nav.Configure(ViewModelLocator.AddNewTodooPage, typeof(AddNewTodooPage));
SimpleIoc.Default.Register<INavigationService>(() => nav);
var mainPage = new NavigationPage(new MainPage());
nav.Initialize(mainPage);
MainPage = mainPage;
}
public static Page GetMainPage()
{
return new MainPage();
}
public static Page GetAddNewTodooPage()
{
return new AddNewTodooPage();
}
}
什麼是錯在這裏與我的註冊視圖模型,它無法解析注入對象?當我運行這段代碼失敗時,它在我添加無參數構造函數時工作,所以我認爲ViewModel沒有在構造函數注入方面正確創建。
如果缺少一些關鍵代碼,請讓我知道,我會發布它。
T.Hanks提前收到任何反饋意見。
順便說一句:我怎麼能設置這個問題解決?我可以做這樣的事嗎? –