C#C
C#2y ago
quantum

WPF DataGrid Not Updating

Hello i have a datagrid and a button on a window. I want to increase a value on datagrid by pressing that button. Value increases on code i can see that with debug but there is no changes on ui.

I am binding source like this on datagrid
ItemsSource="{Binding InventoryItems}"


// This is my viewmodel

class InventoryItemVM : Base
{
    private ObservableCollection<InventoryItem> itemList = [];

    public ObservableCollection<InventoryItem> InventoryItems
    {
        get { return itemList; }
        set { itemList = value; OnPropertyChanged(); }
    }

    private InventoryItem? selectedItem = null;

    public InventoryItem? SelectedItem
    {
        get { return selectedItem; }
        set { selectedItem = value; }
    }

    public void AddStock(int id, int quantity)
    {
        InventoryItem? item = InventoryItems.FirstOrDefault(i => i.ID == id);
        if (item != null)
        {
            item.Quantity += quantity;
            OnPropertyChanged(nameof(InventoryItems));
        }
    }

    public InventoryItemVM()
    {
        InventoryItems =
        [
            new() { ID = 1, Name = "Item 1", Description = "Bla bla", Quantity = 10 },
            new() { ID = 2, Name = "Item 2", Description = "Bla bla", Quantity = 5 },
            new() { ID = 3, Name = "Item 3", Description = "Bla bla", Quantity = 3 }
        ];
    }
}


// And this is my code
InventoryItemVM inventoryDC = new();
public MainWindow()
{
    InitializeComponent();
    this.DataContext = inventoryDC;
}

private void IncreaseButton_Click(object sender, RoutedEventArgs e)
{
    if (inventoryDC.SelectedItem == null)
    {
        ShowErrorMessage("Please select an item to remove.");
        return;
    }

    inventoryDC.AddStock(inventoryDC.SelectedItem.ID, 1);
}
Was this page helpful?