在ViewModel构造函数和导航中添加Api接口将停止Prism的工作



我正在为Xamarin Forms使用VS 17。我已经在我的Xamarin.Forms应用程序中设置了Prism,我只是添加了一个对我的Api接口的引用(在ViewModel Constructor中(,它使应用程序停止导航到第二页。我需要这样做才能通过参数等。我遵循了这个指南:

https://blog.qmatteoq.com/prism-for-xamarin-forms-basic-navigation-and-dependency-injection-part-2/

这就是我让导航停止工作的方法:

private readonly IService _Service;
private ObservableCollection<TodoItem> _topSeries;
public ObservableCollection<TodoItem> TopSeries
{
get { return _topSeries; }
set { SetProperty(ref _topSeries, value); }
}

这是构造函数:

public SecondPageViewModel(IService Service, INavigationService navigationService)   
{
_Service = Service;
_navigationService = navigationService;
}

所以我甚至无法访问上面的视图模型,因为我添加了上面的代码。我试图在DelegateCommand(在第一个ViewModel上(上设置断点,但它只是在InitializeComponent((之后停止;然后什么也没发生。没有错误消息!谢谢

更新:

我的获取数据的服务类:

public class Service : IService
{
public List<TodoItem> TodoList { get; private set; }
HttpClient client;
Service()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
}
public async Task<List<TodoItem>> DataAsync()
{
TodoList = new List<TodoItem>();
var uri = new Uri(string.Format(Constants.RestUrl, string.Empty));
try
{
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
TodoList = JsonConvert.DeserializeObject<List<TodoItem>>(content);
Debug.WriteLine(content);
}
}
catch (Exception ex)
{
Debug.WriteLine(@"ERROR {0}", ex.Message);
}
return TodoList;
}
}

这是我的App.Xaml.cs

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<NavigationPage>();
containerRegistry.RegisterForNavigation<View.MainPage, MainPageViewModel>();
containerRegistry.RegisterForNavigation<View.SecondPage, SecondPageViewModel>();
containerRegistry.Register<IService, Service>();
}

我的界面:

public interface IService
{
Task<List<TodoItem>> DataAsync();
}

这就是我的导航方式(从列表视图点击(:

private EventItem _selectedEvent { get; set; }
public EventItem SelectedEvent
{
get { return _selectedEvent; }  
set
{
if (_selectedEvent != value)
{
if (Device.RuntimePlatform == Device.iOS)
{
_selectedEvent = null;
}
else
{
_selectedEvent = value;
}
NavigationParameters navParams = new NavigationParameters();
navParams.Add("PassedValue", _todoItem.name);
_navigationService.NavigateAsync("SecondPage", navParams);
}
}
}

编辑:

当我在没有ApiService代码的情况下调试时,命令会将我带到新视图模型中的新构造函数。有了代码,它就无法到达构造器。

根据您的代码,您已经声明了这样的构造函数:

Service()
{
// ...
}

您没有设置访问修饰符,因此默认的是internal。以下是定义:

内部类型或成员只能在装配

很可能您的Service.cs已在另一个程序集中声明,而Prism无法访问其构造函数。您的导航不起作用,因为依赖项注入失败。要修复它,只需将您的访问修饰符更改为public:

public Service()
{
// ...
}

最新更新