有多种方法可以解决这个问题。下面是用伪代码表示的一对。首先,协调视图模型:
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;
}
}