Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid Hide RowDetails or Unselect Row

I have a DataGrid who's RowDetails is set to show when selected (RowDetailsVisibilityMode="VisibleWhenSelected"). Now I want to be able to get rid of it! I put a close button on the row details with this code:

private void Button_Click(object sender, RoutedEventArgs e)
  {
   e.Handled = true;
   Button button = sender as Button;
   DataGridRow row = button.FindAncestor<DataGridRow>();

   row.DetailsVisibility = Visibility.Collapsed;
  }

That code gets me 90% there, but once the row details is collapsed for a given row it will not appear the next time that row is selected.

like image 899
Nate Zaugg Avatar asked Mar 17 '10 23:03

Nate Zaugg


2 Answers

I've run into this too. Here's a solution:

Keep that button in the RowDetails and change its code a little. Rather than focusing on the individual row's visibility, set the DataGrid's SelectedIndex property to -1 (none selected).

DataGrid1.SelectedIndex = -1;

Since your RowDetailsVisibilityMode is VisibleWhenSelected, the DataGrid will collapse/hide any expanded RowDetails. This works well when the SelectionMode is Single.

like image 84
Lawrence P. Kelley Avatar answered Sep 18 '22 01:09

Lawrence P. Kelley


You can implement this with the following code in XAML:

<WpfToolkit:DataGrid Name="dgSysthetic" ItemsSource="{Binding}" 
    AutoGenerateColumns="True"      
    SelectionMode="Extended"
    RowDetailsVisibilityMode="Collapsed"
    CanUserAddRows="False" CanUserDeleteRows="False"
    CanUserResizeRows="False" CanUserSortColumns="False"
    RowHeaderWidth="20" RowHeight="25">
    <WpfToolkit:DataGrid.RowHeaderTemplate>
        <DataTemplate>
            <Button Name="btnHideRow" Click="btnHideDetails_Click" FontSize="5">></Button>
        </DataTemplate>
    </WpfToolkit:DataGrid.RowHeaderTemplate>
    <WpfToolkit:DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <WpfToolkit:DataGrid Name="dgAnalytical" ItemsSource="{Binding}" AutoGenerateColumns="True"/>                 
        </DataTemplate>
    </WpfToolkit:DataGrid.RowDetailsTemplate>        
</WpfToolkit:DataGrid>

See the button inside RowHeaderTemplate.

In your C# code you would do this:

private void btnHideDetails_Click(object sender, RoutedEventArgs e) 
    { 
        DependencyObject obj = (DependencyObject)e.OriginalSource; 
        while (!(obj is DataGridRow) && obj != null) obj = VisualTreeHelper.GetParent(obj);

        if (obj is DataGridRow)
        {
            if ((obj as DataGridRow).DetailsVisibility == Visibility.Visible)
            {
                (obj as DataGridRow).DetailsVisibility = Visibility.Collapsed;
            }
            else
            {
                (obj as DataGridRow).DetailsVisibility = Visibility.Visible;
            }
        }                
    }

This worked very well for me.

like image 21
Anderson Avatar answered Sep 20 '22 01:09

Anderson