分层数据,catel和MVVM

时间:2014-01-14 04:32:35

标签: wpf linq data-binding mvvm catel

我正在与Catel,MVVM,WPF合作,我想知道如何使用嵌套/层次数据。

假设我从一个数据库中获得了一个客户列表,每个客户都有一个发票清单,每个清单都有一个InvoiceItem列表。客户拥有许多拥有许多InvoiceItems的发票。

我有一个有效的解决方案,但我不喜欢它。我的方法是构建一个类似于ado.net“数据集”的类集合。类可以代表层次结构的每一层。

这个顶级类CustomerModel将包含一组InvoiceBlocks:

CustomerModel
ObservableCollection< InvoicesBlocks>

每个InvoceBlock都包含一个Invoice和一个InvoiceItems集合:

InvoiceBlock
   发票
ObservableCollection< InvoiceItems>

直到涉及数据绑定路径=声明时,它似乎很聪明。有时候我必须通过电子邮件循环来更新总数,从而击败MVVM的主要卖点。

因此,我决定了解有关使用LINQ查询和数据绑定进行分组的更多信息。这是专业人士的做法吗?

1 个答案:

答案 0 :(得分:0)

您可以做的是让每个视图模型负责使用正确的服务来检索数据。

请注意,我没有使用Catel属性来使其易于理解,但您只需使用Catel.Fody或重写属性即可获得Catel属性。

public class CustomerViewModel
{
    private readonly IInvoiceService _invoiceService;

    public CustomerViewModel(ICustomer customer, IInvoiceService invoiceService)
    {
        Argument.IsNotNull(() => customer);
        Argument.IsNotNull(() => invoiceService);

        Customer = customer;
        _invoiceService = invoiceService;
    }

    public ICustomer Customer { get; private set; }

    public ObservableCollection<IInvoice> Invoices { get; private set; }

    protected override void Initialize()
    {
        var customerInvoices = _invoiceService.GetInvoicesForCustomer(Customer.Id);
        Invoices = new ObservableCollection<IInvoice>(customerInvoices);
    }
}


public class InvoiceViewModel
{
    private readonly IInvoiceService _invoiceService;

    public InvoiceViewModel(IIinvoice invoice, IInvoiceService invoiceService)
    {
        Argument.IsNotNull(() => invoice);
        Argument.IsNotNull(() => invoiceService);

        Invoice = invoice;
        _invoiceService = invoiceService;
    }

    public IInvoice Invoice { get; private set; }

    public ObservableCollection<IInvoiceBlock> InvoiceBlocks { get; private set; }

    protected override void Initialize()
    {
        var invoiceBlocks = _invoiceService.GetInvoiceBlocksForInvoice(Invoice.Id);
        InvoiceBlocks = new ObservableCollection<IInvoiceBlock>(invoiceBlocks);
    }
}

现在你完全控制了什么时候会发生什么。