简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM