I am a complete newbie to WPF and MVVM so I apologise in advance if this query is quite simple. I've searched online and havent been able to find anything which fits my requirements. Hense why I'm here!
I am currently trying to implement a table of data queried from a database using LINQ. This is the query I run:
DataContext connection = new DataContext();
var getTripInformation = from m in connection.tblTrips
where m.TripDate > DateTime.Today
select new { m.TripID, m.TripName, m.TripDate, m.ClosingDate, m.PricePerAdult, m.PricePerChild, m.Status };
Which fills my var with the relevant information which I expect.
Now, what I want to be able to do is diplay this in my View using a DataGrid. Can anyone assist me with this?
In a nutshell, you will have your View and ViewModel. The ViewModel will need to implement the INotifyPropertyChanged interface to facilitate view binding. This just provides an event that is raised when you change a property on your ViewModel. Your View will then bind to the ViewModel's properties. This works as long as the DataContext of the view is set to a ViewModel instance. Below, this is done in code-behind, but many purists do this directly in XAML. Once these relationships are defined, run your LINQ query to populate the ObservableCollection (which also implements INotifyPropertyChanged for when items are added/removed internally) and your grid will show the data.
ViewModel
View (Code-Behind)
View (XAML)
If you set
AutoGenerateColumns = 'True'
on your DataGrid, it will create a row for each public property of the bound item type. If you set this value to false, you will need to explicitly list the columns and what property they will map to.If you are developing the application using MVVM then you need to do-
ViewModel Class - that will have UI logic and will implement INotifyPropertyChanged interface. You need to create Property of type collection which will gets binded with DataGrid. And on setter of this proeprty you need to call PropertyChangedEventHandler.
You need to set the DataContext of View to your ViewModel on XAML, Codebehind, ViewModel or on some mediator class.