HandyControl
HandyControl copied to clipboard
Can't get the ScrollViewer of a ListBox
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
- 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;
}
- 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>
- 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();
}
- Notice how we can get the ScrollViewer of ListBox as expected.
- 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