I need the Expand / Collapse for RowDetailsTemplate

Selecting a Row on the Grid should expand the Row using the RowDetailsTemplate to display the content. This makes that Row the Selected Row and sets the value of the DataGrid's SelectedIndex Property.

To collapse the Row set the DataGrid's SelectedIndex Property to -1.


Check this ...

Adding a Button to a WPF DataGrid

OR

XAML :

<DataGrid Name="dg1" AutoGenerateColumns="False" SelectionMode="Single" CanUserAddRows="false" CanUserDeleteRows="False" SelectionUnit="FullRow" >
    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="BorderThickness" Value="0"/>
        </Style>
    </DataGrid.CellStyle>

    <DataGrid.RowHeaderTemplate>
        <DataTemplate>
            <Expander Expanded="Expander_Expanded" Collapsed="Expander_Collapsed">

            </Expander>
        </DataTemplate>
    </DataGrid.RowHeaderTemplate>

    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" IsReadOnly="True" Width="100" Binding="{Binding Name}" />
        <DataGridTextColumn Header="Title" IsReadOnly="True" Width="100" Binding="{Binding Title}" />
        <DataGridTextColumn Header="Job" IsReadOnly="True" Width="100" Binding="{Binding Job}" />
    </DataGrid.Columns>

    <DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Isi, Converter={StaticResource ResourceKey=isiTextConverter}}" Margin="10,5,0,0" />
        </DataTemplate>
    </DataGrid.RowDetailsTemplate>
</DataGrid>

MainWindow.xaml.cs

private void Expander_Expanded(object sender, RoutedEventArgs e)
{
    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
    if (vis is DataGridRow)
    {
        var row = (DataGridRow)vis;
        row.DetailsVisibility = row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        break;
    }
}

private void Expander_Collapsed(object sender, RoutedEventArgs e)
{
    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
        if (vis is DataGridRow)
        {
            var row = (DataGridRow)vis;
            row.DetailsVisibility = row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
            break;
        }
}

Output

enter image description here