感谢之前在Stack Overflow上得到的一些建议,我在理解MVVM方面取得了良好的进展。然而,当事情变得更加复杂时,我仍然感到困惑。
我有一个视图,用于输入订单。它绑定到OrderScreenViewModel的DataContext。
<StackPanel>
<ComboBox Height="25" Width="100" DisplayMemberPath="CustomerCode" SelectedItem="{Binding Path=Order.Customer}" ItemsSource="{Binding Path=Customers}"></ComboBox>
<ComboBox Height="25" Width="100" DisplayMemberPath="ProductCode" SelectedItem="{Binding Path=CurrentLine.Product}" ItemsSource="{Binding Path=Products}"></ComboBox>
</StackPanel>
第一个组合框用于选择客户。第二个组合框用于为新的订单行选择产品代码。
以下是我无法在MVVM中实现的项目: 1) 当选择客户时,更新产品组合框,以便其项源仅显示具有与组合框中选择的CustomerDto记录相同的CustomerId的产品。 2) 当调用Load时,在客户组合框中设置SelectedItem,使其显示具有等于OrderDto上的CustomerId的客户。 3) 应用与1)相同的过程,以便仅显示/加载属于该客户的产品,并设置Products组合框中的SelectedItem,使其指向与OrderLineDto上包含的ProductId相同的条目。
我不确定如何继续,甚至不确定我的视图模型的职责是否正确。也许这与NotifyPropertyChanged有关?非常感谢您提供了以上信息,如果我做对了,它将极大地帮助我在我的应用程序中。 Alex,谢谢!
public class OrderScreenViewModel
{
public WMSOrderViewModel Order { get; private set; }
public WMSOrderLineViewModel CurrentLine { get; private set; }
public OrderScreenViewModel()
{
Order = new WMSOrderViewModel();
CurrentLine = new WMSOrderLineViewModel(new OrderLineDto());
}
public void Load(int orderId)
{
var orderDto = new OrderDto { CustomerId = 1, Lines = new List<OrderLineDto> { new OrderLineDto{ProductId = 1 }} };
Order = new WMSOrderViewModel(orderDto);
}
public List<CustomerDto> Customers
{
get{
return new List<CustomerDto> {
new CustomerDto{CustomerId=1,CustomerCode="Apple"},
new CustomerDto{CustomerId=1,CustomerCode="Microsoft"},
};
}
}
public List<ProductDto> Products
{
get
{
return new List<ProductDto> {
new ProductDto{CustomerId=1,ProductId=1,ProductCode="P100",Description="Pepsi"},
new ProductDto{CustomerId=1,ProductId=2,ProductCode="P110",Description="Coke"},
new ProductDto{CustomerId=2,ProductId=3,ProductCode="P120",Description="Fanta"},
new ProductDto{CustomerId=2,ProductId=4,ProductCode="P130",Description="Sprite"}
};
}
}
public class WMSOrderLineViewModel
{
private ProductDto _product;
private OrderLineDto _orderLineDto;
public WMSOrderLineViewModel(OrderLineDto orderLineDto)
{
_orderLineDto = orderLineDto;
}
public ProductDto Product { get { return _product; }
set{_product = value; RaisePropertyChanged("Product"); }
}
public class WMSOrderViewModel
{
private ObservableCollection<WMSOrderLineViewModel> _lines;
private OrderDto _orderDto;
public ObservableCollection<WMSOrderLineViewModel> Lines { get { return _lines; } }
private CustomerDto _customer;
public CustomerDto Customer { get{return _customer;} set{_customer =value; RaisePropertyChanged("Customer") }
public WMSOrderViewModel(OrderDto orderDto)
{
_orderDto = orderDto;
_lines = new ObservableCollection<WMSOrderLineViewModel>();
foreach(var lineDto in orderDto.Lines)
{
_lines.Add(new WMSOrderLineViewModel(lineDto));
}
}
public WMSOrderViewModel()
{
_lines = new ObservableCollection<WMSOrderLineViewModel>();
}
}