CodexBloom - Programming Q&A Platform

implementing Binding a Collection of Custom Objects in a WPF DataGrid with MVVM Pattern

šŸ‘€ Views: 2 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-06
wpf mvvm databinding C#

I've looked through the documentation and I'm still confused about I'm experiencing issues when binding a collection of custom objects to a WPF DataGrid while following the MVVM pattern. I have a ViewModel that holds a list of `Person` objects, and I'm trying to display them in a DataGrid. The question is that the DataGrid does not update when I modify the collection (add or remove items) at runtime. Here's the relevant part of my ViewModel: ```csharp using System.Collections.ObjectModel; using System.ComponentModel; public class MainViewModel : INotifyPropertyChanged { public ObservableCollection<Person> People { get; set; } = new ObservableCollection<Person>(); public void AddPerson(string name, int age) { People.Add(new Person { Name = name, Age = age }); OnPropertyChanged(nameof(People)); // Is this necessary? } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } ``` And my XAML for the DataGrid looks like this: ```xml <DataGrid ItemsSource="{Binding People}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Name" Binding="{Binding Name}" /> <DataGridTextColumn Header="Age" Binding="{Binding Age}" /> </DataGrid.Columns> </DataGrid> ``` I created the `ObservableCollection` expecting it to handle the notifications when items are added or removed, so I’m unsure why the UI is not updating. In fact, when I add a new person, I see no behavior messages, and the count in the collection increases, but nothing shows up in the DataGrid. I've also ensured that the `DataContext` of the window is set to an instance of `MainViewModel` in the constructor: ```csharp public MainWindow() { InitializeComponent(); DataContext = new MainViewModel(); } ``` Is there something I'm missing regarding the binding or the DataGrid's update mechanism? Any help would be greatly appreciated! I'm coming from a different tech stack and learning C#.