[英]How to update list<> from another View model on same View in WPF using Caliburn.Micro MVVM?
我是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>();
}
}
我希望將商品添加到購物車。
您可以將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中捕獲事件...
但是為此,您必須修改一些代碼行,但要閱讀鏈接並不復雜
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.