按钮上的WPF MVVM,递增和递减Datagrid单元格值

时间:2018-03-18 09:09:03

标签: c# wpf mvvm

enter image description here

当我点击加号按钮并减去减号按钮

时,如何增加单元格值
public class ProductModel
{
    public decimal Product_Quantity { get; set; }
    ...

viewmodel中的Observeable Collection

private ObservableCollection<ProductModel> mProducts;
public ObservableCollection<ProductModel> Products
{
    get { return mProducts; }
    set { mProducts= value; }
}

SelectedRow

 private ProductModel mSelectedRow;
 public ProductModel SelectedRow
 {
    get => mSelectedRow;
    set
    {
        mSelectedRow = value;
        OnPropertyChanged("SelectedRow");
    }
 }

数据网格绑定

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

这是我想要显示更新值的DataGridTextColumn

<DataGridTextColumn
    Width="auto"
    MinWidth="50"
    Binding="{Binding Product_Quantity}"
    ElementStyle="{StaticResource BlockDataGridTextColumn}"
    Header="Quantity"/>

和最终

private ICommand mIncrementCommand;
    public ICommand IncrementCommand
    {
        get
        {
            if (mIncrementCommand == null)
            {
                mIncrementCommand = new DelegateCommand(delegate ()
                {
                    // logic goes here
                });
            }
            return mIncrementCommand;
        }
    }

更新了,我想要下面的内容

private ICommand mIncrementCommand;
    public ICommand IncrementCommand
    {
        get
        {
            if (mIncrementCommand == null)
            {
                mIncrementCommand = new DelegateCommand(delegate ()
                {
                    SelectedRow.Product_Quantity++;
                });
            }
            return mIncrementCommand;
        }
    }

解决,谢谢Rahul Agarwal

public class ProductModel : BaseViewModel
{
    public decimal Product_Quantity { get; set; }
    ...

我忘了实施INotifyPropertyChanged

1 个答案:

答案 0 :(得分:2)

您需要在ICommand类中使用ProductModel基本属性绑定“+”和“ - ”按钮。比如说:

public ICommand IncrementCommand{ /* provide ICommand execute implementation*/}
public ICommand DecrementCommand{ /* provide ICommand execute implementation*/}

您的execute ICommand实施方法应该注意从Product_Quantity添加/删除。为了反映在结果网格中,Product_Quantity也需要通知 - 因此您的ProductModel也应该实施INotifyPropertyChanged

虽然从您的代码中看不出来,但您需要在ICommand类中使用这些ProductModel实现,而不是主视图模型,因为itemtemplate(每行){{1}的数据上下文1}}是itemcontrol