Detect, if ScrollBar of ScrollViewer is visible or not

BennoDual picture BennoDual · Nov 18, 2013 · Viewed 10.2k times · Source

I have a TreeView. Now, I want to detect, if the vertical Scrollbar is visible or not. When I try it with

var visibility = this.ProjectTree.GetValue(ScrollViewer.VerticalScrollBarVisibilityProperty)

(where this.ProjectTree is the TreeView) I get always Auto for visibility.

How can I do this to detect, if the ScrollBar is effectiv visible or not?

Thanks.

Answer

Thomas Levesque picture Thomas Levesque · Nov 18, 2013

You can use the ComputedVerticalScrollBarVisibility property. But for that, you first need to find the ScrollViewer in the TreeView's template. To do that, you can use the following extension method:

    public static IEnumerable<DependencyObject> GetDescendants(this DependencyObject obj)
    {
        foreach (var child in obj.GetChildren())
        {
            yield return child;
            foreach (var descendant in child.GetDescendants())
            {
                yield return descendant;
            }
        }
    }

Use it like this:

var scrollViewer = ProjectTree.GetDescendants().OfType<ScrollViewer>().First();
var visibility = scrollViewer.ComputedVerticalScrollBarVisibility;