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"&g开发者_如何学Got;
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");
精彩评论