It is possible set the offset for a ListBox? All that I can find is scroll to an element, but I need to scroll the ListBox to any position.
As an alternative, there are any other component that can make virtualize their items, and that I can control the offset?
You can get the ListBox's ScrollViewer and use its ScrollToVerticalOffset-method. To get the ScrollViewer, you can for example hook up to the ListBox's Loaded-event like the following:
XAML:
<ListBox Loaded="HookScrollViewer">
Code-behind:
private void HookScrollViewer(object sender, RoutedEventArgs e)
{
var element = (FrameworkElement)sender;
var scrollViewer = ControlHelpers.FindChildOfType<ScrollViewer>(element);
if (scrollViewer == null)
return;
this.myScrollViewer = scrollViewer;
}
The ControlHerlpers.FindChildOfType-method is implement this way:
public static T FindChildOfType<T>(DependencyObject root) where T : class
{
var queue = new Queue<DependencyObject>();
queue.Enqueue(root);
while (queue.Count > 0)
{
var current = queue.Dequeue();
for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
{
var child = VisualTreeHelper.GetChild(current, i);
var typedChild = child as T;
if (typedChild != null)
{
return typedChild;
}
queue.Enqueue(child);
}
}
return null;
}
Now you have the ListBox's ScrollViewer in the myScrollViewer member and you can directly access its methods. For example, to scroll bottom you can call:
this.myScrollViewer.ScrollToVerticalOffset(double.MaxValue);