Shai UI
Shai UI

Reputation: 51928

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)

Upvotes: 7

Views: 7297

Answers (3)

AnthonyWJones
AnthonyWJones

Reputation: 189457

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");

Upvotes: 1

Shai UI
Shai UI

Reputation: 51928

I think I got it....

myScrollViewer.ApplyTemplate();

ScrollBar s = myScrollViewer.Template.FindName("PART_VerticalScrollBar", myScrollViewer) as ScrollBar;

Upvotes: 14

Jon
Jon

Reputation: 437386

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.

Upvotes: 3

Related Questions