WPF: How to programmatically extract Scrollbar from ScrollViewer?

I would like to access the scrollbar from my ScrollViewer.

I think it is hidden somewhere in the ScrollViewer template, do I have a way to access and get a link to it programmatically?

So, if I have

<ScrollViewer x:Name="myScrollViewer"> 

In the code behind which I would like to go:

 ScrollBar scrollBar = myScrollViewer.GetScrollBar(); 

(obviously, I guess that would be harder than simple)

+6
source share
3 answers

I think I understand ...

 myScrollViewer.ApplyTemplate(); ScrollBar s = myScrollViewer.Template.FindName("PART_VerticalScrollBar", myScrollViewer) as ScrollBar; 
+13
source

You will need to use the VisualTreeHelper.GetChild method to view the ScrollViewer visual tree to find the ScrollBar .

Since this method provides very low-level functionality and using it in high-level code will be painful, you probably want to use a wrapper like LINQ to visual tree .

+3
source

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"); 
+1
source

Source: https://habr.com/ru/post/895693/


All Articles