Oct 15, 2010

WPF DataGrid Controlling the Scrollbar

I just started with WPF controls and one of the issues I came through is controlling the scrollbar in WPF objects. In WPF you have logical and visual trees. To get the scrollbar, Microsoft recommendation is to go trough the tree to get the scroll bar. So find my implementation below.

/// Method to get scrollbar in a visual object
private static ScrollViewer GetScrollbar(DependencyObject dep)
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dep); i++)
        var child = VisualTreeHelper.GetChild(dep, i);
        if (child != null && child is ScrollViewer)
            return child as ScrollViewer;
            ScrollViewer sub = GetScrollbar(child);
            if (sub != null)
                return sub;
    return null;

ScrollViewer scrollView = GetScrollbar(myDataGrid);

It should work with other objects too, but I only tried with a WPF Datagrid.  I lost some time to figure out how to do this, hope it helps.