Home > Back-end >  C# WPF DataGrid Binding MVVM - Binding master ViewModel (container of child ViewModels) to DataGrid
C# WPF DataGrid Binding MVVM - Binding master ViewModel (container of child ViewModels) to DataGrid

Time:09-01

I have two C# (VS 2019 - .Net Framework 4.8) ViewModels, AllAirportsVM and AirportVM.

An instance of AllAirportsVM maintains a List<AirportVM> and has a bindable member CurrentAirport of type AirportVM.

I have a DataGrid in an AllAirportsView and I would like to set its ItemSource to the List<AirportVM> of my instance of AllAirportsVM, where I understand the DataGrid's DataContext, for purposes of defining the contents of its columns, should be the class AirportVM.

But if the DataGrid's DataContext is set to a class of ViewModel (AirportVM), how then do I bind my instance of AllAirportsVM to the DataGrid, such that when the user selects a row in the DataGrid, the CurrentAirport property of my instance of AllAirportsVM gets set/updated?

I have limited experience working with DataTemplates and RelativeSources so wondered if the solution to my problem involved them somehow and I just wasn't aware.

Thanks in advance for any advice or links to other articles or discussions that might help me.

CodePudding user response:

the datagrid should look something like

<!--Datacontext here is AllAirportsVM-->
<DataGrid ItemsSource="{Binding AllAirportsVM}" SelectedItem="{Binding CurrentAirport}">
    <DataGrid.Columns>
        <!-- columns bind to Properties of a AirportVM-->
        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
        <DataGridTextColumn Header="Country" Binding="{Binding Country}"/>
    </DataGrid.Columns>
</DataGrid>

CodePudding user response:

The DataContext of the DataGrid (or rather its parent window or UserControl) should be an instance of the AllAirportsVM view model class.

You would then bind the ItemsSource property directly to the List<AirportVM> property of the view model:

<DataGrid ItemsSource="{Binding Airports}" />

By default, the DataGrid will then generate a column per each public property of the AirportVM.

So, in other words, if you bind the ItemsSource to an IEnumerable<T> property, you will get a column for each public property of the type T (where T is AirportVM in your case).

  • Related