Binding DataGrid to DataTable. DataGrid's ItemSource is null on first load. - WPF
I'm trying to bind a DataGrid to a DataTable located in my viewmodel. The columns are dynamic hence why I'm binding to a DataTable and adding the columns and rows in the viewmodel. The relevant VM code looks like:
private DataTable _data;public DataTable Data{ get => _data; set { _data = value; OnPropertyChanged(); }}// called in VM's constructor. Also tried calling it in the view's code-behind in loaded event.public void LoadData(){ Data = new DataTable(); Data.BeginLoadData(); // adding columns using Data.Columns.Add // adding rows using Data.Rows.Add Data.EndLoadData();}
private DataTable _data;public DataTable Data{ get => _data; set { _data = value; OnPropertyChanged(); }}// called in VM's constructor. Also tried calling it in the view's code-behind in loaded event.public void LoadData(){ Data = new DataTable(); Data.BeginLoadData(); // adding columns using Data.Columns.Add // adding rows using Data.Rows.Add Data.EndLoadData();}
Now the viewmodel is created before the view, and the view's datacontext is set to the viewmodel when the view is created. The xaml for the DataGrid is:
There are certain columns I need to hide based on a list of strings in the VM. So I checked in both the View's Loaded event and the DataGrid's Loaded event, and in both cases the ItemSource is null, so I can't access the columns to hide them. Why would it be null if it is bound to the DataTable in the vm?
Recent Announcements
Continue the conversation
Join the Discord to ask follow-up questions and connect with the community
C
C#
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.