Detect, if ScrollBar of ScrollViewer is visible or not

≯℡__Kan透↙ 提交于 2020-06-11 17:00:53

问题


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.


回答1:


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;



回答2:


ComputedVerticalScrollBarVisibility instead of VerticalScrollBarVisibility

VerticalScrollBarVisibility sets or gets the behavior, whereas the ComputedVerticalScrollBarVisibility gives you the actual status.

http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.computedverticalscrollbarvisibility(v=vs.110).aspx

You cannot access this property the same way you did in your code example, see Thomas Levesque's answer for that :)




回答3:


Easiest approach I've found is to simply subscribe to the ScrollChanged event which is part of the attached property ScrollViewer, for example:

<TreeView ScrollViewer.ScrollChanged="TreeView_OnScrollChanged">
</TreeView>

Codebehind:

private void TreeView_OnScrollChanged(object sender, ScrollChangedEventArgs e)
{
    if (e.OriginalSource is ScrollViewer sv)
    {
        Debug.WriteLine(sv.ComputedVerticalScrollBarVisibility);
    }
}

For some reason IntelliSense didn't show me the event but it works.



来源:https://stackoverflow.com/questions/20048431/detect-if-scrollbar-of-scrollviewer-is-visible-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!