Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix getting the wrong Ancestor (ScrollViewer) at CustomValidationPopup #4123

Merged
merged 1 commit into from
Jun 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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