【发布时间】:2019-08-07 05:12:00
【问题描述】:
是否可以在 ViewModel 中有一个构造函数来初始化数据服务?
我的数据服务正在以类似这样的方式访问数据存储的网络服务:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Cirrious.MvvmCross.ViewModels;
using Cirrious.MvvmCross.Commands;
using MobSales.Logic.DataService;
using MobSales.Logic.Base;
using MobSales.Logic.Model;
namespace MobSales.Logic.ViewModels
{
public class CustomersViewModel:MvxViewModel
{
ICustomerService custService;
public CustomersViewModel(ICustomerService custService)
{
this.custService = custService;
if (custService != null)
{
custService.LoadCustomerCompleted += new EventHandler<CustomerLoadedEventArgs>(custService_LoadCustomerCompleted);
}
loadCustomerCommand = new MvxRelayCommand(LoadCustomer);
loadCustomerCommand.Execute();
}
private ObservableCollection<Customer> customers;
public ObservableCollection<Customer> Customers
{
get { return customers; }
set
{
customers = value;
FirePropertyChanged("Customers");
}
}
private CustomerViewModel customer;
public CustomerViewModel Customer
{
get { return customer; }
set
{
customer = value;
FirePropertyChanged("Customer");
}
}
private MvxRelayCommand loadCustomerCommand;
public MvxRelayCommand LoadCustomerCommand
{
get { return loadCustomerCommand; }
}
public void LoadCustomer()
{
custService.LoadCustomer();
}
void custService_LoadCustomerCompleted(object sender, CustomerLoadedEventArgs e)
{
if (e.Error != null)
{
return;
}
List<Customer> loadedCustomers = new List<Customer>();
foreach (var cust in e.Customers)
{
loadedCustomers.Add(new Customer(cust));
}
Customers = new ObservableCollection<Customer>(loadedCustomers);
}
}
我遇到了异常,但只能看到以下部分描述:
Cirrious.MvvmCross.Exceptions.MvxException: Failed to load ViewModel for type MobSales.Logic.ViewModels.CustomersViewModel from locator MvxDefau…
从 View 到 ViewModel 的绑定是如我在这篇文章中所展示的那样实现的:MVVMCross Bindings in Android
谢谢!
【问题讨论】:
-
我对 ViewModels 的理解是,它确实与获取数据等无关。
-
是的,没错,我只会初始化(错误的词...批准会更好)我的数据服务。获取数据会发生在其他地方。你可以看到,我有一个加载完成的事件......
-
如果在你的 ViewModel 中没有发生,为什么你的 ViewModel 必须有这个数据服务?
-
仅适用于这个 custService_LoadCustomerCompleted 和这个 LoadCustomer
标签: c# xamarin.android mvvmcross