title: WPF datagrid collapse details row on click
body: <p>I needed to collapse the details row of a WPF DataGrid when a user clicked on it, and re-display it when they clicked again.  I also wanted to preserve the DataGridRoDetailsVisibilityMode of VisibleWhenSelected, using single selection.</p>
  
  <p>I came up with this solution, based off of this post elsewhere: <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/0a45b3a7-46d0-45a9-84b2-0062f07f6fec#eadc8f65-fcc6-41df-9ab9-8d93993e114c" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/0a45b3a7-46d0-45a9-84b2-0062f07f6fec#eadc8f65-fcc6-41df-9ab9-8d93993e114c</a></p>
  
  <pre><code>    private bool _rowSelectionChanged;
  
  
      private void dgCompletedJobs_SelectionChanged(object sender, SelectionChangedEventArgs e)
      {
          _rowSelectionChanged = true;
      }
  
      private void dgCompletedJobsMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
      {
          DependencyObject dep = (DependencyObject)e.OriginalSource;
  
          //navigate up the tree
          while (dep != null &amp;&amp;
              !(dep is DataGridCell) &amp;&amp;
              !(dep is DataGridColumnHeader))
          {
              dep = VisualTreeHelper.GetParent(dep);
          }
  
          if (dep == null)
          {
              return;
          }
  
          DataGridCell dgc = dep as DataGridCell;
          if (dgc != null)
          {
              //navigate further up the tree
              while (dep != null &amp;&amp; !(dep is DataGridRow))
              {
                  dep = VisualTreeHelper.GetParent(dep);
              }
  
              DataGridRow dgr = dep as DataGridRow;
              DataGrid dg = sender as DataGrid;
              if (dg != null &amp;&amp; dgr != null)
              {
                  if (dgr.IsSelected &amp;&amp; !_rowSelectionChanged)
                  {
                      dg.RowDetailsVisibilityMode =
                          (dg.RowDetailsVisibilityMode == DataGridRowDetailsVisibilityMode.VisibleWhenSelected)
                              ? DataGridRowDetailsVisibilityMode.Collapsed
                              : DataGridRowDetailsVisibilityMode.VisibleWhenSelected;
                  }
                  else
                  {
                      dg.RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.VisibleWhenSelected;
                  }
              }
          }
          _rowSelectionChanged = false;
      }
  </code></pre>
  
  <p>This appears to solve my problem nicely, but I have a haunting suspicion that this could be done more simply and elegantly, especially since I'm using MVVM on this project.  However, I see this as an acceptable usage of event-driven code-behind, because it's purely presentation logic.</p>
  
  <p>Does anyone have a cleaner solution?</p>