Daniel Peñalba
Daniel Peñalba

Reputation: 31847

Change ScrollBar width in ScrollViewer programatically

When I create a new ScrollViewer, I need to modify the size of the ScrollBars in the ScrollViewer (change the VerticalScroll width and the HorizontalScroll height), programatically.

I tried the following based in a solution found in SO, without success:

    public static ScrollViewer CreateScrollViewer()
    {
        ScrollViewer result = new ScrollViewer();
        // I need to set the scroll width and height here
        // I tried the following with no success
        result.Resources.Add(SystemParameters.VerticalScrollBarWidth, 100);
        return result;
    }

I saw some solutions to change them, but all are XAML based. I need to do it in runtime, in pure C#. How could I do this?

Upvotes: 2

Views: 2142

Answers (1)

Sheridan
Sheridan

Reputation: 69959

You can access the ScrollBars from the ScrollViewer's ControlTemplate. You can find out how to do that from the How to: Find ControlTemplate-Generated Elements page on MSDN and you can find details of the default ControlTemplate in the ScrollViewer Styles and Templates page on MSDN, but in short, try this:

ScrollViewer scrollViewer = new ScrollViewer();
scrollViewer.ApplyTemplate();
ScrollBar scrollBar = 
    (ScrollBar)scrollViewer.Template.FindName("PART_VerticalScrollBar", scrollViewer);

You can do the same for the horizontal ScrollBar which is named PART_HorizontalScrollBar.

Upvotes: 1

Related Questions