Vilx-
Vilx-

Reputation: 107042

How to add scrollbars to your custom control in WPF?

After asking this question I realized that perhaps I should have asked a more generic question. So, here goes:

In WPF, I'm creating a custom Panel-derived control. To that control I would like to add horizontal and vertical scrollbars and control them myself (get & set min/max/value/pagesize). How can I do this?

This is my first encounter with WPF, and I'm not yet familiar with Templates and Styles, so I don't know if answer lies there or somewhere else.

Upvotes: 2

Views: 4678

Answers (3)

Anthony Nichols
Anthony Nichols

Reputation: 1678

The Scroll Viewer needs to be in the template, around the border in the default setup:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type control:MyCustomControl}">
            <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
                <Border Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">                        
                    <ItemsPresenter />
                </Border>                        
            </ScrollViewer>
        </ControlTemplate>
    </Setter.Value>
</Setter>

Upvotes: 0

Vilx-
Vilx-

Reputation: 107042

OK, I found it! Three easy steps:

  1. Implement System.Windows.Controls.Primitives.IScrollInfo on your custom control;
  2. Add your custom control to a ScrollViewer;
  3. Set the CanContentScroll property on the ScrollViewer to True.

Voila!

Upvotes: 2

Anvaka
Anvaka

Reputation: 15823

Yes. The answer lies not in the Panel but in the ScrollViewer. Your panel shouldn't take care about scrollbars. Let ScrollViewer measure and arrange your panel. So your visual tree will include ScrollViewer first, then your panel:

    <ScrollViewer> 
      <cc:YourPanel/>
    </ScrollViewer>

If you want to control ScrollViewer, you will probably want to either inherit from it or customize its template.

Upvotes: 1

Related Questions