Find width of a scrollbar

354 views Asked by At

Same as this question, but for UWP. In particular, I can't find any SystemParameters class, so the answer there does not work in my case.

Also important: If at all possible, I would like to be able to get the width a scrollbar would have if it existed. In other words, there are cases where the scrollbar does not exist yet, but user input is likely to cause it to be created. In such a case, I want to be able to know what width it is expected to have if/when it is created. (I realize something unexpected might cause the answer to be wrong; that's ok, as long as I'm getting the usual expected answer.)

2

There are 2 answers

1
Jay Zuo On BEST ANSWER

As @Neme's answer said, you can use VisualTreeHelper to retrieve the ScrollBar and then use ActualWidth property to get its width.

However, if you didn't change VerticalScrollBar's styles and templates, the width of VerticalScrollBar would always be 12. You can find this in ScrollBar styles and templates.

<Style TargetType="ScrollBar">
    <Setter Property="MinWidth" Value="12" />
    <Setter Property="MinHeight" Value="12" />
    ...
</Style

For VerticalScrollBar, its width won't change so its ActualWidth would always be 12. And for HorizontalScrollBar, its height won't change so its ActualHeight would always be 12. These value changes only when we change scrollbar's style or template. And in this scenario, we should know the width we've set, or we can retrieve it at runtime by using VisualTreeHelper.

0
Neme On

As far as I know, there is no better way other than digging in the properties yourself. There really is a lot of hacking you have to do in UWP. For example, it looks like there is no way to get the ScrollBar from a ScrollViewer directly (you also can't do FindName on the template or even derive from it to use GetTemplateChild), but these lines should work around that:

var rootElement = (FrameworkElement)VisualTreeHelper.GetChild(scrollViewer, 0);
var scrollBar = (ScrollBar)rootElement.FindName("VerticalScrollBar");

You could access the ActualWidth property of the ScrollBar, but that will be zero if it's not visible. Luckily, I found out that MinWidth contains the right value.

You do have to have a visible ScrollViewer.