I'd like to access the Scrollbar from within my ScrollViewer.
I think it's hidden somewhere within the ScrollViewer's template, is there a way for me to access, and get a reference to it programmatically?
So if I have
<ScrollViewer x:Name="myScrollViewer">
In the code behind I'd like to go:
ScrollBar scrollBar = myScrollViewer.GetScrollBar();
(obviously, I assume it'd be trickier than just that)
The ScrollViewer Control There are two predefined elements that enable scrolling in WPF applications: ScrollBar and ScrollViewer. The ScrollViewer control encapsulates horizontal and vertical ScrollBar elements and a content container (such as a Panel element) in order to display other visible elements in a scrollable area.
However, you can use the ScrollViewer element by itself because it is a composite control that encapsulates ScrollBar functionality. The ScrollViewer control responds to both mouse and keyboard commands, and defines numerous methods with which to scroll content by predetermined increments.
Physical scrolling is the default scroll behavior for most Panel elements. WPF supports both types of scrolling. The IScrollInfo interface represents the main scrolling region within a ScrollViewer or derived control.
Content and data focused Windows applications often require vertical and/or horizontal scrolling functionality to conveniently display large content on the screen. The WPF ScrollViewer control can be used to implement vertical and horizontal scrolling on Windows controls.
I think I got it....
myScrollViewer.ApplyTemplate();
ScrollBar s = myScrollViewer.Template.FindName("PART_VerticalScrollBar", myScrollViewer) as ScrollBar;
You will need to use the VisualTreeHelper.GetChild
method to walk the visual tree of the ScrollViewer
to find the ScrollBar
.
Since this method provides very low-level functionality and using it in high-level code will be painful, you will probably want to utilize a wrapper like LINQ to visual tree.
Get the VisualTreeEnumerator
code from this blog article.
With this extension class in place:-
ScrollBar s = myScrollViewer.Decendents()
.OfType<ScrollBar>()
.FirstOrDefault(sb => sb.Name == "PART_VerticalScrollBar");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With