我是WPF的新手,我想使用Caliburn Micro遵循MVVM框架。我一直无法从另一个视图模型更新视图模型中的列表。
我有3个视图:
在“产品视图”中单击“产品”时,应在“购物车视图”中添加产品
POSViewModel.cs
public class POSViewModel : Conductor<object>.Collection.AllActive
{
#region Private Variables
private ProductsViewModel _ProductsViewModel;
private CartViewModel _CartViewModel;
#endregion
#region Public Variables
public ProductsViewModel ProductsViewModel
{
get { return _ProductsViewModel; }
set { _ProductsViewModel = value; }
}
public CartViewModel CartViewModel
{
get { return _CartViewModel; }
set { _CartViewModel = value; }
}
#endregion
#region Public Methods
public POSViewModel()
{
ProductsViewModel = new ProductsViewModel();
CartViewModel = new CartViewModel();
}
#endregion
}
ProductsViewModel.cs:在AddProdClick(ProductModel productModel)上,我想将单击的产品添加到CartView。
public class ProductsViewModel : Conductor<object>
{
public BindableCollection<ProductModel> Products { get; set; }
public ProductsViewModel()
{
Products = new BindableCollection<ProductModel>();
for (int i = 0; i < 25; i++)
{
Products.Add(new ProductModel
{
ProductName = "Product" + i.ToString(),
Qty = i + 2,
Rate = i * 10
}); ;
}
}
public void AddProdClick(ProductModel productModel)
{
}
}
ProductView.xaml:它是一个具有产品列表的用户控件。产品按钮已绑定到视图模型中的AddProdClick。
<Button Content="Add To Cart" cal:Message.Attach="AddProdClick($datacontext)" />
CartViewModel.cs
public class CartViewModel : Conductor<object>
{
private BindableCollection<ProductModel> _CartProducts;
public BindableCollection<ProductModel> CartProducts
{
get
{
return _CartProducts;
}
set
{
NotifyOfPropertyChange(() => CartProducts);
_CartProducts = value;
}
}
public CartViewModel()
{
CartProducts = new BindableCollection<ProductModel>();
}
}
我希望将商品添加到购物车。
答案 0 :(得分:0)
您可以将CartViewModel用作Args:
public POSViewModel()
{
CartViewModel = new CartViewModel();
ProductsViewModel = new ProductsViewModel(CartViewModel);
}
并在ProductsViewModel的构造器中使用
public class ProductsViewModel : Conductor<object>
{
public BindableCollection<ProductModel> Products { get; set; }
public CartViewModel CVM { get; set; }
public ProductsViewModel(CartViewModel CVM)
{
this.CVM = CVM;
}
public void AddProdClick(ProductModel productModel)
{
CVM.Add(productModel)
}
}
您还有另一种解决方案:使用PosViewModel:
public POSViewModel()
{
CartViewModel = new CartViewModel();
ProductsViewModel = new ProductsViewModel(this);
}
public class ProductsViewModel : Conductor<object>
{
public BindableCollection<ProductModel> Products { get; set; }
public CartViewModel CVM { get; set; }
public ProductsViewModel(POSViewModel PVM)
{
this.CVM = PVM.CartViewModel;
}
public void AddProdClick(ProductModel productModel)
{
CVM.Add(productModel)
}
}
第三个解决方案是使用EventAggregator,您需要修改一些编码
单击时,您将在Add方法中执行EventAggregator.publish(new Addevent)
并在PosviewModel中捕获事件...
但是为此,您必须修改一些代码行,但是阅读链接并不复杂