簡體   English   中英

單擊WPF MVVM,遞增和遞減Datagrid單元格值

[英]WPF MVVM, Increment and Decrement Datagrid Cell Value on Button Click

在此處輸入圖片說明

當我單擊加號按鈕並減小減號按鈕時如何增加單元格值

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

ViewModel中的可觀察集合

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

您需要將“ +”和“-”按鈕與ProductModel類中的ICommand基本屬性綁定。 像這樣說:

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

您的ICommand實現的execute方法應注意從Product_Quantity添加/刪除。 為了在結果網格中反映出來, Product_Quantity還需要通知-因此您的ProductModel還應該實現INotifyPropertyChanged

盡管從代碼itemcontrol它,但是您需要在ProductModel類中而不是在主視圖模型中具有這些ICommand實現,因為itemcontrol itemtemplate (每行)的數據上下文是ProductModel

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM