是否有可能在視圖模型中有一個構造函數來初始化數據服務? (不要誤會我的意思,我的數據服務正在訪問數據存儲的Web服務)類似這樣的東西(被問到,因爲我得到了ViewLoader引發的異常「無法加載ViewModel ...」而且它不會顯示整個例外...):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:無法加載視圖模型從定位MvxDefau型MobSales.Logic.ViewModels.CustomersViewModel ...
從View到ViewModel的綁定被實現,就像我在這篇文章中發佈的那樣:MVVMCross Bindings in Android
謝謝!
我對ViewModels的理解是,它的確沒有與提取數據等有關。 – Styxxy
是的,我只會初始化(錯誤的單詞...批准會更好)我的數據服務。獲取數據會發生在別的地方。你可以看到,我有一個加載完成的事件... – Martin
如果它沒有發生在你的ViewModel中,爲什麼你的ViewModel必須有這個數據服務? – Styxxy