Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 261
Veikedo Avatar asked Jan 20 '26 21:01

Veikedo


1 Answers

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}"
like image 70
Niko Carrizo Avatar answered Jan 22 '26 11:01

Niko Carrizo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!