Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: How to extract Scrollbar From ScrollViewer programmatically?

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)

like image 286
Shai UI Avatar asked Aug 23 '11 16:08

Shai UI


People also ask

What is ScrollViewer in WPF?

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.

Can I use the ScrollViewer element by itself?

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.

What are the different types of scrolling in WPF panels?

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.

How do I implement vertical and horizontal scrolling on Windows controls?

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.


3 Answers

I think I got it....

myScrollViewer.ApplyTemplate();

ScrollBar s = myScrollViewer.Template.FindName("PART_VerticalScrollBar", myScrollViewer) as ScrollBar;
like image 54
Shai UI Avatar answered Oct 04 '22 03:10

Shai UI


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.

like image 44
Jon Avatar answered Oct 04 '22 02:10

Jon


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");
like image 24
AnthonyWJones Avatar answered Oct 04 '22 03:10

AnthonyWJones