public static partial class Extensions
{
public static T FindAncestor<T>(DependencyObject obj) where T : DependencyObject
{
while (obj != null)
{
T o = obj as T;
if (o != null)
return o;
obj = VisualTreeHelper.GetParent(obj);
}
return null;
}
public static T FindAncestor<T>(this UIElement obj) where T : UIElement
{
return FindAncestor<T>((DependencyObject)obj);
}
public static void CollapseAllRow(this DataGrid dg)
{
foreach (var rowItem in dg.ItemsSource)
{
// Ensures that all rows are loaded.
dg.ScrollIntoView(rowItem, dg.Columns.Last());
// Get the content of the cell.
FrameworkElement el = dg.Columns.Last().GetCellContent(rowItem);
// Retrieve the row which is parent of given element.
DataGridRow row = DataGridRow.GetRowContainingElement(el.Parent as FrameworkElement);
// Sometimes some rows for some reason can be null.
if (row != null)
row.DetailsVisibility = Visibility.Collapsed;
}
}
}