I have a model, of the form:
public class A
{
public ObservableCollection B col1;
}
Public Class B
{
public int BA;
public int BB;
public ObservableCollection C;
}
public Class C
{
public int CA;
public int CB;
}
The first DataGrid is filled with the content of A, which is nothing more than a list of B elements.
<DataGrid x:Name="GrillaA" AutoGenerateColumns="False" IsReadOnly="True" SelectionMode="Single" ItemsSource="{Binding Mode=OneWay}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding BA}"/>
<DataGridTextColumn Binding="{Binding BB}"/>
</DataGrid.Columns>
</DataGrid>
And then I have another grid, which is filled with the content of the list that contains B (the list of objects C)
<DataGrid x:Name="GrillaB" AutoGenerateColumns="False" IsReadOnly="True" SelectionMode="Single" ItemsSource="{Binding SelectedItem.C, ElementName=GrillaA}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding CA}"/>
<DataGridTextColumn Binding="{Binding CB}"/>
</DataGrid.Columns>
</DataGrid>
All this is going perfectly... except that under each grid I have some text boxes that are filled with the content of the selected row in the grid... In the case of the first grid, I have no problem, they fill perfectly...
The question is: when I select an item in GridA, how do I select the first element of GridB, in an MVVM model, in such a way that the fields below that grid are filled?
EDITION
I leave an example in git:
https://github.com/topcatarg/MVVMGridsTest
and no, beyond the first screen, on the second screen when selecting an item from the first grid, the second grid does not select the first item (because the selection property is executed twice)
What you should do is add the property
SelectedIndex
with properties of your View Model to your grids, both in GridA and GridB:So in your ViewModel you add the two properties, and in the setter of the first one (which will be executed when the selected index changes in
GrillaA
) you will be able to change the index of the other grid:This is a possible solution, there are others but I usually go for this one.
edited
I will present another solution, since when using a property of
SelectedItem
the first grid to load theItemsSource
second one, the first proposed solution did not work correctly.First, we must add the dependency property to gridB in the binding of ,
ItemsSource
so that we are notified when the . Afterwards, we simply subscribe to the gridB event and select the first index there. Example:NotifyOnTargetUpdated
true
ItemsSource
TargetUpdated
XAML:
Event handler: