I have a collection of Visual
s in a ListBox
. I need to find the XPosition
of an element inside it and then animate the HorizontalOffset
of the ListBox
's ScrollViewer
. Essentially I want to created an animated ScrollIntoView
method.
This gives me a couple of problems. Firstly, how can I get a reference to the ListBox
s scrollviewer? Secondly, how can i get the relative XPosition
or HozintalOfffset
of an arbitrary element in the ListBox
?
I'm not reponding to any input on the ListBox
itself so I can't use Mouse
related properties.
I don't think you will be able to use a WPF storyboard for the animation because storyboards animate WPF dependency properties. You will need to call
ScrollViewer.ScrollToHorizontalOffset(double)
to scroll.You could try creating a custom dependency property that calls SetHorizontalOffset in the OnDependencyPropertyChanged() function. Then you could animate this property.
To get the scroll viewer you can use the VisualTreeHelper to search the visual children of the ListBox. Save a reference to the ScrollViewer because you will need it later. Try this:
This function returns the first visual child of the parameter type. Call
FindVisualChild<ScrollViewer>(ListBox)
to get the ScrollViewer.Finally, try using
UIElement.TranslatePoint(Point, UIElement)
to get the X position of the item. Call this function on the item, pass in 0,0 for the point, and pass in the ScrollViewer.Hope this helps.
I'm not sure if my method is good practice but for the limited time I had it seemed to work okay. Instead of using a story board I just used a DispatcherTimer instead.
Make sure it's a DispatchTimer so the thread is able to take control of the UI element
Also remember to bind to your object in your view!