Reputation:
I have a ScrollViewer and in that I am showing the Vertical Scrollbar, Now on changing resolution of the system I want to get the width of the scrollbar. I went through One StackOverflow Post there they mention to check for SystemParameters.ScrollWidth Property but again I din find any help from their. Can anybody please help me to fix my issue. Any answer will be appreciated.
Upvotes: 28
Views: 21500
Reputation: 28968
As suggested by some answers, SystemParameters.VerticalScrollBarWidth
returns the constant that is used for system controls.
However, this value is not reliable. For example, the ScrollBar
elements could have been customized or have their visibility set to Visibility.Collapsed
(so that they are no longer a child of the visual tree and therefore not impacting the rendered layout anymore).
To get the current width you must locate the scroll bars in the visual tree of the ScrollViewer
.
The ScrollViewer
defines the ScrollBar
elements as template parts named "PART_VerticalScrollBar"
and "PART_HorizontalScrollBar"
.
You can use the following extension method (extending DependencyObject
) to get the vertical ScrollBar
:
Usage
For example, to get the ScrollBar
width of the vertical ScrollViewer
of the DataGrid
control use
if (dataGrid.TryFindVisualChildElementByName("PART_VerticalScrollBar", out ScrollBar scrollbar))
{
double verticalScrolBarWidth = scrollbar.Width;
}
public static class VisualTreeHelperExtensions
{
public static bool TryFindVisualChildElementByName<TChild>(
this DependencyObject parent,
string childElementName,
out TChild resultElement) where TChild : FrameworkElement
{
resultElement = null;
if (parent is Popup popup)
{
parent = popup.Child;
if (parent == null)
{
return false;
}
}
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if (child is FrameworkElement frameworkElement
&& frameworkElement.Name.Equals(childElementName, StringComparison.OrdinalIgnoreCase))
{
resultElement = frameworkElement as TChild;
return true;
}
if (child.TryFindVisualChildElementByName<TChild>(childElementName, out resultElement))
{
return true;
}
}
return false;
}
}
Upvotes: 1
Reputation: 1336
I am not sure if this is the correct answer. Every WPF control can be restyled so even the scrollbar. So SystemParameters.VerticalScrollBarWidth works only if it is used as default scrollbar. The correct solution would be to find the vertical scrollbar in the visual tree and measure it's ActualWidth. It is the most precise measurement.
Upvotes: 12
Reputation: 158309
I think SystemParameters.VerticalScrollBarWidth
is what you are looking for.
Upvotes: 49