Skip to content

Commit 54c0b0a

Browse files
authored
Merge pull request #4123 from MahApps/fix/4117
Fix getting the wrong Ancestor (ScrollViewer) at CustomValidationPopup
2 parents 5c5fd39 + 6601baa commit 54c0b0a

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/MahApps.Metro/Controls/CustomValidationPopup.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ private void CustomValidationPopup_Loaded(object? sender, RoutedEventArgs e)
144144
this.scrollViewer.ScrollChanged -= this.ScrollViewer_ScrollChanged;
145145
}
146146

147-
this.scrollViewer = adornedElement.TryFindParent<ScrollViewer>();
147+
this.scrollViewer = adornedElement.GetVisualAncestor<ScrollViewer>();
148148
if (this.scrollViewer != null)
149149
{
150150
this.scrollViewer.ScrollChanged += this.ScrollViewer_ScrollChanged;

src/MahApps.Metro/Controls/TreeHelper.cs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,7 @@ public static IEnumerable<DependencyObject> GetAncestors(this DependencyObject c
6363

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

81+
/// <summary>
82+
/// Tries to find and returns a visual ancestor, starting at the leaf.
83+
/// <para>If element is not of <see cref="Visual"/> or <see cref="Visual3D"/> the logical ancestry is used.</para>
84+
/// </summary>
85+
/// <param name="leaf">The starting object.</param>
86+
/// <returns></returns>
87+
public static T? GetVisualAncestor<T>(this DependencyObject? leaf)
88+
where T : DependencyObject
89+
{
90+
while (leaf is not null)
91+
{
92+
if (leaf is T ancestor)
93+
{
94+
return ancestor;
95+
}
96+
97+
leaf = leaf is Visual or Visual3D
98+
? VisualTreeHelper.GetParent(leaf)
99+
: LogicalTreeHelper.GetParent(leaf);
100+
}
101+
102+
return default(T);
103+
}
104+
82105
/// <summary>
83106
/// Finds a Child of a given item in the visual tree.
84107
/// </summary>

0 commit comments

Comments
 (0)