views:

418

answers:

1

I have a text box with verticalscrollbarvisibility set to auto. I would like to do a test to find out if the scrollbar is actually visible during runtime. I have tried the statement:

if (textbox1.VerticalScrollBarVisibility == ScrollBarVisibility.Visible)

but it does not work. Any ideas?

A: 

First place the following extension method in static class (either place the class in the same namespace as the rest of your code or in namespace included with a using statement in your code file):-

public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
{
 int count = VisualTreeHelper.GetChildrenCount(root);
 for (int i = 0; i < count; i++)
 {
  var child = VisualTreeHelper.GetChild(root, i);
  yield return child;
  foreach (var descendent in Descendents(child))
   yield return descendent;
 }
}

With this extension method available you can dig out the ScrollViewer inside the text box which is responsible for the scroll bar and test its ComputedVerticalScrollBarVisibility.

if (textbox1.Descendents().OfType<ScrollViewer>()
  .FirstOfDefault().ComputedVerticalScrollBarVisibility == Visibility.Visible)
AnthonyWJones
Hi Anthony,I think I may be missing something. I get the following errors when I try to implement this:1.)'System.Windows.Controls.ScrollViewer' is a 'type' but is used like a variable2.)No overload for method 'OfType' takes '1' arguments
Weston Goodwin
Oops both are actually the same problem, typed the syntax of OfType wrong, answer adjusted
AnthonyWJones