Veikedo
Veikedo

Reputation: 1503

Binding DataGrid selected row in another DataGrid

I have a class Book:

class Book
{
 public int Id {get; set;}
 public string Title {get; set;}
 public string Authors {get; set;}
 public string Genre {get; set;}
 public virtual ICollection <Publication> Publications {get; set;}
}

On the form there are two (let there be A and B) DataGrids: A displays a list of Book objects, B displays the elements in Publications of selected book (ie binding to a selected line in A) .

The question is how to bind a B to the current row in the A?

I do so but in my opinion it's not quite correct:

<DataGrid x:Name="BooksGrid"
          ItemsSource="{Binding Path=WorkingBooksSet, Mode=TwoWay}"
          IsSynchronizedWithCurrentItem="True" RowDetailsVisibilityMode="VisibleWhenSelected"
          AutoGenerateColumns="False">
  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Path=Id}" Width="Auto" />
    <DataGridTextColumn Binding="{Binding Path=Title}" Width="*" />
    <DataGridTextColumn Binding="{Binding Path=Authors}" Width="*" />
    <DataGridTextColumn Binding="{Binding Path=Genre}" Width="*" />
  </DataGrid.Columns>


  <DataGrid.RowDetailsTemplate>
    <DataTemplate>
      // Second DataGrid
      <DataGrid ItemsSource="{Binding ElementName=BooksGrid, Path=SelectedItem.Publications}"
                AutoGenerateColumns="False">
        <DataGrid.Columns>
          <DataGridTextColumn Binding="{Binding Path=Publisher}" />
          <DataGridTextColumn Binding="{Binding Path=ISBN}" />
          ...
        </DataGrid.Columns>
      </DataGrid>

    </DataTemplate>
  </DataGrid.RowDetailsTemplate>
</DataGrid>

WorkingBooksSet is ObservableCollection in my ViewModel


So I found a solve in this binding cheat sheet.

Upvotes: 3

Views: 2134

Answers (1)

Niko Carrizo
Niko Carrizo

Reputation: 86

I would suggest having a SelectedBook property in your ViewModel and bind DataGrid A's selected item to it.

SelectedItem = "{Binding SelectedBook}"

Then, set DataGrid B's ItemsSource to the publications property.

ItemsSource="{Binding SelectedBook, Path=Publications}"

Upvotes: 1

Related Questions