Wednesday, August 22, 2012

WPF ScrollViewer Control Example


There are two controls that enables scrolling in WPF: ScrollBar and ScrollViewer. The ScrollViewer encapsulates both vertical and horizontal ScrollBar and a container that contains all the visible elements inside scrollable area. I'll show a ScrollBar example based on code described in my previous post.
WPF ScrollViewer example

Let's see the XAML:
<ScrollViewer HorizontalScrollBarVisibility="Auto" 
                VerticalScrollBarVisibility="Auto">               
    <Expander Name="MyExpander" Margin="10,10" >
        <Expander.Content>
            <DataGrid Name="dataGrid1"
                Cursor="Hand"
                ItemsSource="{Binding Employees}" />
        </Expander.Content>
        <Expander.Style>
            <Style TargetType="Expander">
                <Setter Property="IsExpanded" Value="False" />
                <Setter Property="Header" Value="Click to See More" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsExpanded,RelativeSource={RelativeSource Self}}"                                 Value="True">
                        <Setter Property="Header" Value="Click to See Less" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Expander.Style>
    </Expander>                
</ScrollViewer>
By specifying HorizontalScrollBarVisibility and VerticalScrollBarVisibility as "Auto" we achieve that ScrollBar becomes visible only when content becomes larger than window frame.
Download the source code (Visual Studio 2010 project).

2 comments: