wpf 检测 ScrollViewer 的 ScrollBar 是否可见
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20048431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect, if ScrollBar of ScrollViewer is visible or not
提问by BennoDual
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.
(this.ProjectTree 是 TreeView)我总是自动获得可见性。
How can I do this to detect, if the ScrollBar is effectiv visible or not?
我怎样才能做到这一点来检测 ScrollBar 是否有效可见?
Thanks.
谢谢。
回答by Thomas Levesque
You can use the ComputedVerticalScrollBarVisibilityproperty. But for that, you first need to find the ScrollViewerin the TreeView's template. To do that, you can use the following extension method:
您可以使用该ComputedVerticalScrollBarVisibility物业。但为此,您首先需要ScrollViewer在TreeView的模板中找到。为此,您可以使用以下扩展方法:
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;
回答by oerkelens
ComputedVerticalScrollBarVisibility instead of VerticalScrollBarVisibility
ComputedVerticalScrollBarVisibility 而不是 VerticalScrollBarVisibility
VerticalScrollBarVisibility sets or gets the behavior, whereas the ComputedVerticalScrollBarVisibility gives you the actual status.
VerticalScrollBarVisibility 设置或获取行为,而 ComputedVerticalScrollBarVisibility 为您提供实际状态。
You cannot access this property the same way you did in your code example, see Thomas Levesque's answer for that :)
您无法像在代码示例中那样访问此属性,请参阅 Thomas Levesque 对此的回答:)
回答by Shahin Dohan
Easiest approach I've found is to simply subscribe to the ScrollChangedevent 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 没有向我展示该事件,但它有效。

