public static Control FindNearestStatefulControl()

in src/BehaviorsSDKManaged/Microsoft.Xaml.Interactivity/VisualStateUtilities.cs [78:112]


        public static Control FindNearestStatefulControl(FrameworkElement element)
        {
            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }

            // Try to find an element which is the immediate child of a UserControl, ControlTemplate or other such "boundary" element
            FrameworkElement parent = element.Parent as FrameworkElement;

            // bubble up looking for a place to stop
            while (!VisualStateUtilities.HasVisualStateGroupsDefined(element) && VisualStateUtilities.ShouldContinueTreeWalk(parent))
            {
                element = parent;
                parent = parent.Parent as FrameworkElement;
            }

            if (VisualStateUtilities.HasVisualStateGroupsDefined(element))
            {
                // Once we've found such an element, use the VisualTreeHelper to get it's parent. For most elements the two are the 
                // same, but for children of a ControlElement this will give the control that contains the template.
                Control templatedParent = VisualTreeHelper.GetParent(element) as Control;

                if (templatedParent != null)
                {
                    return templatedParent;
                }
                else
                {
                    return element as Control;
                }
            }

            return null;
        }