如何更新现有行的值而不是添加新行

时间:2018-03-20 03:29:05

标签: c# wpf mvvm

我想要的首先如何检测项目是否已经存在。如果项目已存在于Datagrid行中,则插入新行更新该特定项目而不是添加新行

public class ProductModel: BaseViewModel
{
    public int Product_ID { get; set; }
    public string Product_Name { get; set; }
    public decimal Product_Quantity { get; set; }
    .....

Observeable Collection

    private ObservableCollection<ProductModel> mProducts { get; set; } = null;
    public ObservableCollection<ProductModel> Products
    {
        get
        {
            mProducts = mProducts ?? new ObservableCollection<ProductModel>();
            return mProducts;
        }
    }

绑定到Datagrid

ItemsSource="{Binding Products}"
SelectedItem="{Binding SelectedRow}"

这是如何将项目添加到集合

 Products.Add(new ProductModel{ Product_ID = 1, Product_Name = "Product Name 1", Product_Quantity = 1 });
 Products.Add(new ProductModel{ Product_ID = 2, Product_Name = "Product Name 2", Product_Quantity = 5 });
 Products.Add(new ProductModel{ Product_ID = 3, Product_Name = "Product Name 3", Product_Quantity = 2 });

下面我的逻辑应该去哪里。如果项目exsits然后更新已存在的行,则添加新行

private ICommand mAddItemCommand;
    public ICommand AddItemCommand
    {
        get
        {
            if (mAddItemCommand== null)
            {
                mAddItemCommand = new DelegateCommand(delegate ()
                {
                    Products.Add(new ProductModel{ Product_ID = 2, Product_Name = "Product Name 2", Product_Quantity = 1 });
                });
            }
            return mAddItemCommand;
        }
    }

单击上面命令,其中Product_ID为2,Product_Quantity应该变为6,之前为5。

对不起解释错误.. 提前谢谢

1 个答案:

答案 0 :(得分:1)

创建一个可执行所需功能的方法

public void AddProduct(ProductModel product) {
    var item = Products.FirstOrDefault(_ => _.Product_ID == product.Product_ID);
    if(item != null) {
        item.Product_Quantity += product.Product_Quantity;
    } else {
        Products.Add(product);
    }
}

并在代表中使用要添加或更新的项目进行调用。

//...
delegate () {
    ProductModel product = //However you intend on getting the item
    AddProduct(product);
}
//...