HandyControl icon indicating copy to clipboard operation
HandyControl copied to clipboard

Can't get the ScrollViewer of a ListBox

Open rampaa opened this issue 1 week ago • 0 comments

Describe the bug

I need to access the underlying ScrollViewer used by the ListBox. When I don't use HandyControl, I can access it as expected but when I use HandyControl I can't access it.

Steps to reproduce the bug

  1. Create the following extension method:
    public static T? GetChildOfType<T>(this DependencyObject dependencyObject) where T : DependencyObject
    {
        int childrenCount = VisualTreeHelper.GetChildrenCount(dependencyObject);
        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(dependencyObject, i);
            if (child is T result)
            {
                return result;
            }

            T? grandChild = GetChildOfType<T>(child);
            if (grandChild is not null)
            {
                return grandChild;
            }
        }

        return null;
    }
  1. Create a window that has a ListBox like
        <ListBox VirtualizingStackPanel.VirtualizationMode="Recycling" Focusable="False"
                  ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                  VirtualizingPanel.IsVirtualizingWhenGrouping="True" VirtualizingPanel.ScrollUnit="Pixel"
                  ScrollViewer.CanContentScroll="True" VirtualizingPanel.IsVirtualizing="True"
                  ScrollViewer.VerticalScrollBarVisibility="Auto" VirtualizingPanel.IsContainerVirtualizable="True"
                  HorizontalContentAlignment="Stretch"
                  Background="Transparent"
                  x:Name="MyListBox">
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="Focusable" Value="False" />
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>
  1. On that window's code-behind override the OnSourceInitialized event like following:
    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        ScrollViewer myTextBoxScrollViewer = MyListBox.GetChildOfType<ScrollViewer>();
        myTextBoxScrollViewer!.ScrollToTop();
    }
  1. Notice how we can get the ScrollViewer of ListBox as expected.
  2. Now add HandyControl to the project and observe we cannot get the ScrollViewer anymore thus getting a NullReferenceException when we try to use it.

Expected behavior

We should be able to access the underlying ScrollViewer in the same way we can when we don't use HandyControl

Screenshots

No response

NuGet package version

None

IDE

No response

Framework type

No response

Windows version

No response

Additional context

No response

rampaa avatar Jun 26 '24 23:06 rampaa