简体   繁体   English

检测,如果ScrollViewer的ScrollBar可见或不可见

[英]Detect, if ScrollBar of ScrollViewer is visible or not

I have a TreeView. 我有一个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. (其中this.ProjectTree是TreeView)我总是获得Auto以获得可见性。

How can I do this to detect, if the ScrollBar is effectiv visible or not? 如果ScrollBar有效可见,我该如何检测?

Thanks. 谢谢。

You can use the ComputedVerticalScrollBarVisibility property. 您可以使用ComputedVerticalScrollBarVisibility属性。 But for that, you first need to find the ScrollViewer in the TreeView 's template. 但为此,您首先需要在TreeView的模板中找到ScrollViewer 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;

ComputedVerticalScrollBarVisibility instead of VerticalScrollBarVisibility ComputedVerticalScrollBarVisibility而不是VerticalScrollBarVisibility

VerticalScrollBarVisibility sets or gets the behavior , whereas the ComputedVerticalScrollBarVisibility gives you the actual status. VerticalScrollBarVisibility设置或获取行为 ,而ComputedVerticalScrollBarVisibility为您提供实际状态。

http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.computedverticalscrollbarvisibility(v=vs.110).aspx 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 :) 您无法像在代码示例中那样访问此属性,请参阅Thomas Levesque对此的回答:)

Easiest approach I've found is to simply subscribe to the ScrollChanged event which is part of the attached property ScrollViewer , for example: 我发现最简单的方法是简单地订阅ScrollChanged事件,该事件是附加属性ScrollViewer ,例如:

<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. 出于某种原因,IntelliSense没有向我展示该事件,但它有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM