Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF accessing scrollviewer of a listview codebehind

I need to access the scrollviewer of a listview from the codebehind. here is the definition of my listview

<ListView Grid.Row="1" ItemsSource="{Binding Path=SpecList, UpdateSourceTrigger=PropertyChanged}"  
                            Name="mylistview"
                            ItemTemplate="{StaticResource SpecElementTemplate}"
                            Background="{StaticResource EnvLayout}"
                            ScrollViewer.HorizontalScrollBarVisibility="Visible"
                            ScrollViewer.VerticalScrollBarVisibility="Disabled"
                            ItemContainerStyle="{StaticResource MyStyle}"
                            BorderBrush="Blue"
                            BorderThickness="20"
                            Margin="-2">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
</ListView>

How can I get the scrollviewer?

Thank you

Andrea

like image 616
andrea Avatar asked Mar 27 '17 17:03

andrea


1 Answers

There are several ways to get the ScrollViewer. Simplest solution is to get the the first child of the first child of the ListView. This means get the Border and the ScrollViewer inside this Border like described in this answer:

// Get the border of the listview (first child of a listview)
Decorator border = VisualTreeHelper.GetChild(mylistview, 0) as Decorator;

// Get scrollviewer
ScrollViewer scrollViewer = border.Child as ScrollViewer;

A second way is to scan all childrens recursive to find the ScrollViewer. This is described in the answer by Matt Hamilton in this question. You can simply use this function to get the ScrollViewer.

ScrollViewer scrollViewer = GetChildOfType<ScrollViewer>(mylistview);

This second solution is much more generic and will also work if the template of your ListView was edited.

like image 106
Fruchtzwerg Avatar answered Oct 05 '22 10:10

Fruchtzwerg