diff --git a/Microsoft.Toolkit.Uwp.UI/Extensions/FrameworkElement/FrameworkElementExtensions.RelativeAncestor.cs b/Microsoft.Toolkit.Uwp.UI/Extensions/FrameworkElement/FrameworkElementExtensions.RelativeAncestor.cs index 8dbdf9dd251..385388d5d3b 100644 --- a/Microsoft.Toolkit.Uwp.UI/Extensions/FrameworkElement/FrameworkElementExtensions.RelativeAncestor.cs +++ b/Microsoft.Toolkit.Uwp.UI/Extensions/FrameworkElement/FrameworkElementExtensions.RelativeAncestor.cs @@ -27,14 +27,14 @@ public static object GetAncestor(DependencyObject obj) /// FrameworkElement public static void SetAncestor(DependencyObject obj, object value) { - obj.SetValue(AncestorProperty, value); + obj.SetValue(AncestorProperty, new WeakReference(value)); } /// /// Attached for retrieving a parent for the /// public static readonly DependencyProperty AncestorProperty = - DependencyProperty.RegisterAttached("Ancestor", typeof(object), typeof(FrameworkElementExtensions), new PropertyMetadata(null)); + DependencyProperty.RegisterAttached("Ancestor", typeof(WeakReference), typeof(FrameworkElementExtensions), new PropertyMetadata(null)); /// /// Gets the Type of Ancestor to look for from this element. @@ -80,6 +80,7 @@ private static void FrameworkElement_Loaded(object sender, RoutedEventArgs e) { if (sender is FrameworkElement fe) { + fe.Loaded -= FrameworkElement_Loaded; SetAncestor(fe, fe.FindAscendant(GetAncestorType(fe))); } } diff --git a/UnitTests/UnitTests.UWP/Extensions/Test_FrameworkElementExtensions.cs b/UnitTests/UnitTests.UWP/Extensions/Test_FrameworkElementExtensions.cs new file mode 100644 index 00000000000..c39354fd3eb --- /dev/null +++ b/UnitTests/UnitTests.UWP/Extensions/Test_FrameworkElementExtensions.cs @@ -0,0 +1,108 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Toolkit.Uwp; +using Microsoft.Toolkit.Uwp.UI; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Threading.Tasks; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Markup; + +namespace UnitTests.Extensions +{ + [TestClass] + public class Test_FrameworkElementExtensions : VisualUITestBase + { + [Ignore] + [TestCategory("FrameworkElementExtensions")] + [TestMethod] + public async Task Test_Ancestor_WeakReference() + { + // Need to sim loading the control, and not just load the XAML via XamlReader + await App.DispatcherQueue.EnqueueAsync(async () => + { + var treeRoot = XamlReader.Load( + @" + + +