C# 购物车是模型还是视图模型?
我正在尝试在我的应用程序中实现一个购物车系统,这被证明比我预期的更令人困惑/困难 目前,我的实现如下所示:C# 购物车是模型还是视图模型?,c#,mvvm,C#,Mvvm,我正在尝试在我的应用程序中实现一个购物车系统,这被证明比我预期的更令人困惑/困难 目前,我的实现如下所示: public class CartItem { public Product Product { get; set; } public int Quantity { get; set; } public decimal Subtotal { get { return Quantity * Product.Price; } } } public class Cart
public class CartItem
{
public Product Product { get; set; }
public int Quantity { get; set; }
public decimal Subtotal { get { return Quantity * Product.Price; } }
}
public class Cart
{
public ObservableCollection<CartItem> CartItems { get; set; }
public int ItemCount { get; set; }
public decimal Total { get; set; }
public ICommand AddItemCommand { get; set; }
public ICommand RemoveItemCommand { get; set; }
public void AddItem(Product product)
{
}
public void RemoveItem(Product product)
{
}
}
公共类CartItem
{
公共产品产品{get;set;}
公共整数数量{get;set;}
公共小数小计{获取{返回数量*产品.价格;}}
}
公共类购物车
{
公共ObservableCollection CartItems{get;set;}
公共int ItemCount{get;set;}
公共十进制总数{get;set;}
公共ICommand AddItemCommand{get;set;}
public ICommand removietemcommand{get;set;}
公共无效附加项(产品)
{
}
公共无效删除项(产品)
{
}
}
具体来说,我很难找到它在MVVM模式中的位置。此实现将一直工作,直到购物车项目
上的数量
变量被它所属的购物车
以外的内容(例如视图)修改为止
我问了自己一些问题:
- 购物车是对象的抽象吗?是=>这是一个模型
- 它将被序列化/反序列化到数据库或从数据库中进行序列化/反序列化吗?是的,所以它还是一个模型
- 它是否为视图提供数据?对这是一个视图模型
- 它是否作用于或修改该数据?是的,所以它是一个视图模型
我认为ICommand和方法不应该存在。所有ICommand必须放在ViewModel类中。CartItem肯定是一个模型。Cart更像是视图绑定到的控制器,因此在ViewModel中,当存储在
Cart.CartItems
集合中的一个CartItem
上的CartItem.Quantity
发生更改时,您的实际问题是“如何更新视图中的Cart.ItemCount
和Cart.Total
”,或者“这些类当前代表MVVM模式的哪一部分:模型、视图模型还是视图?”是的。我的意思是,不。肯定是。可能是nes。可能是。