Skip to content

Commit

Permalink
(#4117) Fix getting the wrong Ancestor (ScrollViewer) at CustomValida…
Browse files Browse the repository at this point in the history
…tionPopup
  • Loading branch information
punker76 committed Jun 10, 2021
1 parent 5c5fd39 commit 6601baa
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/MahApps.Metro/Controls/CustomValidationPopup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ private void CustomValidationPopup_Loaded(object? sender, RoutedEventArgs e)
this.scrollViewer.ScrollChanged -= this.ScrollViewer_ScrollChanged;
}

this.scrollViewer = adornedElement.TryFindParent<ScrollViewer>();
this.scrollViewer = adornedElement.GetVisualAncestor<ScrollViewer>();
if (this.scrollViewer != null)
{
this.scrollViewer.ScrollChanged += this.ScrollViewer_ScrollChanged;
Expand Down
27 changes: 25 additions & 2 deletions src/MahApps.Metro/Controls/TreeHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ public static IEnumerable<DependencyObject> GetAncestors(this DependencyObject c

/// <summary>
/// Returns full visual ancestry, starting at the leaf.
/// <para>If element is not of <see cref="Visual"/> or <see cref="Visual3D"/> the
/// logical ancestry is used.</para>
/// <para>If element is not of <see cref="Visual"/> or <see cref="Visual3D"/> the logical ancestry is used.</para>
/// </summary>
/// <param name="leaf">The starting object.</param>
/// <returns></returns>
Expand All @@ -79,6 +78,30 @@ public static IEnumerable<DependencyObject> GetVisualAncestry(this DependencyObj
}
}

/// <summary>
/// Tries to find and returns a visual ancestor, starting at the leaf.
/// <para>If element is not of <see cref="Visual"/> or <see cref="Visual3D"/> the logical ancestry is used.</para>
/// </summary>
/// <param name="leaf">The starting object.</param>
/// <returns></returns>
public static T? GetVisualAncestor<T>(this DependencyObject? leaf)
where T : DependencyObject
{
while (leaf is not null)
{
if (leaf is T ancestor)
{
return ancestor;
}

leaf = leaf is Visual or Visual3D
? VisualTreeHelper.GetParent(leaf)
: LogicalTreeHelper.GetParent(leaf);
}

return default(T);
}

/// <summary>
/// Finds a Child of a given item in the visual tree.
/// </summary>
Expand Down

0 comments on commit 6601baa

Please sign in to comment.