How do I load a DataGrid with data from a database using WPF and MVVM?

c#-4.0, mvvm, wpf, wpfdatagrid

Solution

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

public class MyViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private ObservableCollection<MyRecord> _records = null;
    public ObservableCollection<MyRecord> Records 
    {
        get { return _records; }
        set
        {
            if( _records != value )
            {
                _records = value;

                if( this.PropertyChanged != null )
                {
                    this.PropertyChanged( this, new PropertyChangedEventArgs( "Records" ) );
                }
             }
         }
    }

    public MyViewModel()
    {
        this.Records = new ObservableCollection<MyRecord>();
        this.LoadData();
    }

    private void LoadData()
    {
        // this populates Records using your LINQ query
    }

View (Code-Behind)

public class MyView : UserControl
{
    public MyView()
    {
        InitializeControl();

        // setup datacontext - this can be done directly in XAML as well
        this.DataContext = new MyViewModel();
    }
}

View (XAML)

<DataGrid
    ItemsSource="{Binding Path=Records, Mode=OneWay}"
    ...
/>

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.

Problem

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?

Original source