MVVM事件 - 它们应该如何以及在哪里进行MVVM架构?

时间:2010-08-22 16:16:13

标签: wpf wpf-controls

假设我有这个主窗口xmal:

<Window x:Class="MVVMTUTRIALS.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:views="clr-namespace:TestMvvm444.Views"
Title="Window1" Height="300" Width="400" Loaded="Window_Loaded">
<Grid>
    <views:CustomersList x:Name="CustomersList"/>
    <views:CustomerBoughtList x:Name="CustomerBoughtList"/>
</Grid>
</Window>

我想要一个在CustomersList(点击cerrtian raw)中调用规则的事件 CustomerBoughtList(显示所有这个客户购买)做某事,所以我的q是:

1.事件应该在哪里?在主窗口中思考是否合理?

2.有人请指导我该怎么办?

我认为我误解的核心是如何将UserControl彼此通信以及与视图模型进行通信

谢谢你们阅读和做笔记。

2 个答案:

答案 0 :(得分:1)

有各种方法可以解决这个问题。这里有一对用伪代码表示。首先,协调视图模型:

public class CustomersViewModel : ViewModel
{
    public event EventHandler<EventArgs> SelectedCustomerChanged;

    public ICollection<Customer> Customers
    {
        get ...
    }

    public CustomerViewModel SelectedCustomer
    {
        get ...
        set ...
    }
}

public class CustomerPurchasesViewModel : ViewModel
{
    public CustomerViewModel Customer
    {
        get ...
        set ...
    }

    public ICollection<PurchaseViewModel> Purchases
    {
        get ...
    }
}

public class MainViewModel : ViewModel
{
    private CustomersViewModel customers;
    private CustomerPurchasesViewModel customerPurchases;

    public MainViewModel(CustomersViewModel customers, CustomerPurchasesViewModel customerPurchases)
    {
        this.customers = customers;
        this.customerPurchases = customerPurchases;

        // push changes in selection to the customer purchases VM
        this.customers.SelectedCustomerChanged += delegate
        {
            this.customerPurchases.Customer = this.customers.SelectedCustomer;
        };
    }
}

其次,使用调解员:

public class CustomersViewModel : ViewModel
{
    public ICollection<Customer> Customers
    {
        get ...
    }

    public CustomerViewModel SelectedCustomer
    {
        get ...
        set
        {
            ...
            eventHub.Publish(new CustomerSelectedMessage(value));
        }
    }
}

public class CustomerPurchasesViewModel : ViewModel, ISubscriber<CustomerSelectedMessage>
{
    public CustomerViewModel Customer
    {
        get ...
        set ...
    }

    public ICollection<PurchaseViewModel> Purchases
    {
        get ...
    }

    private void Receive(CustomerSelectedMessage m)
    {
        this.Customer = e.Customer;
    }
}

public class MainViewModel : ViewModel
{
    private CustomersViewModel customers;
    private CustomerPurchasesViewModel customerPurchases;

    public MainViewModel(CustomersViewModel customers, CustomerPurchasesViewModel customerPurchases)
    {
        this.customers = customers;
        this.customerPurchases = customerPurchases;
    }
}

答案 1 :(得分:-1)

您可以拥有主窗口的视图模型,该窗口具有您的用户控件可以绑定的两个公共列表属性。然后,当在视图中更改选择时,您可以在视图模型列表中检测到该选项,并执行您需要对其他列表执行的操作。视图中没有事件处理。