I have a treeview in Silverlight 3.
The treeview is bound to a observable collection - which contains a list of hierarchical data.
When the page loads initially, all nodes, by default, in the treeview, are collapsed.
I have functionality that allows a certain item in the treeview to be selected programmatically.
The problem that I am running into is when an item is selected that isn't immediately visible (i.e. one or more parent nodes are collapsed). I programmatically expand them, but, when I try to programmatically scroll into view, so the user can see the selected item, it doesn't work.
I looked into this further, and I believe that it has to do with the calculated viewport height for the scroll viewer. It almost seems like a timing issue, as, if the item's parent node is expanded, and then the item is programmatically selected, the code that scrolls the treeview into view for that selected treeview item works perfectly.
Please refer to the extension method below that I am using to scroll the treeview into view. Any help or suggestions on how to correct this would be greatly appreciated.
Thanks.
public static void BringIntoViewForScrollViewer(this FrameworkElement frameworkElement, ScrollViewer scrollViewer)
{
var transform = frameworkElement.TransformToVisual(scrollViewer);
var positionInScrollViewer = transform.Transform(new Point(0, 0));
if (positionInScrollViewer.Y < 0 || positionInScrollViewer.Y > scrollViewer.ViewportHeight)
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + positionInScrollViewer.Y - ScrollPadding);
}