Accessing the implicit ScrollViewer of a Flyout in WinUI in code

70 views Asked by At

I have a Flyout with content that is longer than the length of the Flyout, so a vertical scrollbar is activated. I wish to get the underlying ScrollViewer so that I can reset the scroll position everytime the Flyout is closed.

Tried getting the content of the flyout, but could not find the ScrollViewer in the Visual Tree.

1

There are 1 answers

0
Andrew KeepCoding On BEST ANSWER

This should work using the Closing event:

private void Flyout_Closing(FlyoutBase sender, FlyoutBaseClosingEventArgs args)
{
    if (VisualTreeHelper
        .GetOpenPopupsForXamlRoot(this.XamlRoot)
        .FirstOrDefault() is not { } popup ||
        popup.Child.FindDescendant<ScrollViewer>() is not { } scrollViewer)
    {
        return;
    }

    _ = scrollViewer.ChangeView(horizontalOffset: 0, verticalOffset: 0, zoomFactor: null, disableAnimation: true);
}

NOTE

FindDescendant comes from the CommunityToolkit.WinUI.Extensions NuGet package. Of course, you should be able to also use the VisualTreeHelper to get the ScrollViewer.