Afternoon all.
As we know, a WPF listbox contains a scrollviewer.
We can access the scrollviewer in XAML such as;
<ListBox Scrollviewer.CanContentScroll="False" />
However, how would I access the scrollviewer from code?
There is no ".Scrollviewer" for me to access, so I tried casting, which failed.
Can anybody suggest how I can access the scrollviewer?
-
-
CanContentScroll is a dependency property on ScrollViewer. You can set it like this: ScrollViewer.SetCanContentScroll(listBox1, false);
-
OK bad example lol
Im actually trying to get access to one of the methods (ScrollToVerticalOffset)
sorry for the rubbish example lol -
jh71283 wrote:OK bad example lol
Im actually trying to get access to one of the methods (ScrollToVerticalOffset)
sorry for the rubbish example lol
ListBox.ScrollIntoView doesn't work for you? If not, you're going to have to walk the visual tree to find the ScrollViewer. -
No, unfortunately ScrollIntoView is no use to me, because I have 2 listboxes that I have to keep at identical scroll positions.
How would I go about 'walking the visual tree'?
-
How about
((System.Windows.Controls.ScrollViewer)listBox1).ScrollToVerticalOffset(offset);
?I recommend Reflector or Visual Studio's Object Browser for examining the WPF class hierarchy.
-
something like this maybe?
http://www.brunowouters.be/download/ListBoxScroll.zip -
Bruno - Brilliant! that is exactly what i was looking for, and works perfectly.
For reference, Bruno has used
FindVisualChild<ScrollViewer>(ListboxName);
to find the scrollviewer, and it works like a charm.private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject {
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) {
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem) {
return (childItem)child;
} else {
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null) {
return childOfChild;
}
}
}
return null;
} -
And in VB;
Me.FindVisualChild(Of ScrollViewer)(Me.ListBoxName)
Private Function FindVisualChild(Of childItem As DependencyObject)(ByVal obj As DependencyObject) As childItem
Dim i As Integer
For i = 0 To VisualTreeHelper.GetChildrenCount(obj) - 1
Dim child As DependencyObject = VisualTreeHelper.GetChild(obj, i)
If ((Not child Is Nothing) AndAlso TypeOf child Is childItem) Then
Return DirectCast(child, childItem)
End If
Dim childOfChild As childItem = Me.FindVisualChild(Of childItem)(child)
If (Not childOfChild Is Nothing) Then
Return childOfChild
End If
Next i
Return CType(Nothing, childItem)
End Function
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.