Displaying Information When Clicking a DataGrid Row
I have DataGrid
one that displays a list of classes for a professor. I want to have the professor click on the line on DataGrid
and then display the students who are in that class.
Is this possible with WPF?
In the datagrid add the following sections:
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<DataGrid ItemsSource="{Binding students}">
</DataGrid>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
If you want to display details within a line, @AnsonWoody wrote an answer. If you want to display details outside in a separate control, use SelectedItem
for DateGrid
or CurrentItem
for CollectionViewSource
.
Assuming your datacontext contains elements in ClassesWithStudents
, and each element has a property Students
, you can do the following:
<StackPanel x:Name="panel1">
<StackPanel.Resources>
<CollectionViewSource x:Key="classesCollection" Source="{Binding ClassesWithStudents}"/>
</StackPanel.Resources>
<DataGrid x:Name="dg1" ItemsSource="{Binding Source={StaticResource classesCollection}}">
</DataGrid>
<!-- Bind current item with path=/ -->
<ContentControl Content="{Binding Source={StaticResource classesCollection},Path=/Students}"/>
<!-- Bind selected item -->
<ContentControl Content="{Binding ElementName=dg1,Path=SelectedItem.Students}"/>
</StackPanel>
Of course, it ContentControl
is only a placeholder. If it Students
is a collection, use something like <ItemsControl ItemsSource="{Binding Source={StaticResource classesCollection},Path=/Students}"/>
or something suitable for your needs to get a nice representation of the student.