ItemsControl: get SelectionChanged on a DataGrid (MVVM pattern)

62 views Asked by At

I have an item control that will populate datagrid with data from an ObservableCollection TrayTypesDataGrids

private ObservableCollection<ObservableCollection<TrayType>> trayTypesDataGrids;
            <ItemsControl x:Name="DataGridControl" ItemsSource="{Binding TrayTypesDataGrids}" HorizontalAlignment="Center" DockPanel.Dock="Top">
                <ItemsControl.Template>
                    <ControlTemplate>
                        <DockPanel IsItemsHost="True" Height="{Binding Path=ActualHeight, ElementName=DataGridControl}"/>
                    </ControlTemplate>
                </ItemsControl.Template>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <DataGrid Style="{StaticResource DataGridStyleDetails}" ItemsSource="{Binding}">
                            <DataGrid.Columns>
                                <DataGridTextColumn Header="ID" Binding="{Binding ID}" ElementStyle="{StaticResource TBColumn}"/>
                                <DataGridTextColumn Header="Name" Binding="{Binding Name}" ElementStyle="{StaticResource TBColumn}"/>
                                <DataGridTextColumn Header="D" Binding="{Binding D}" ElementStyle="{StaticResource TBColumn}"/>
                                <DataGridTextColumn Header="W" Binding="{Binding W}" ElementStyle="{StaticResource TBColumn}"/>
                            </DataGrid.Columns>
                        </DataGrid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

This works and all the DataGrids are populated correctly. However, I want to capture when the selection changes.

How can I do this in an MVVM way?

I tried using Selection Changed on the DataGrid element, however this means I have to set this up on the view.

                        <DataGrid Style="{StaticResource DataGridStyleDetails}" ItemsSource="{Binding}" SelectionChanged="DataGrid_SelectionChanged">
                            <DataGrid.Columns>
                                <DataGridTextColumn Header="ID" Binding="{Binding ID}" ElementStyle="{StaticResource TBColumn}"/>
                                <DataGridTextColumn Header="Name" Binding="{Binding Name}" ElementStyle="{StaticResource TBColumn}"/>
                                <DataGridTextColumn Header="D" Binding="{Binding D}" ElementStyle="{StaticResource TBColumn}"/>
                                <DataGridTextColumn Header="W" Binding="{Binding W}" ElementStyle="{StaticResource TBColumn}"/>
                            </DataGrid.Columns>
                        </DataGrid>

Is there a way to capture the selection changed in the model?

0

There are 0 answers