Forum Xamarin.Forms

Access to scrollview in control template

MikilllMikilll Member ✭✭✭

In one of my views in code-behind, I want to call scrollView.ScrollToAsync. Unfortunately, my scrollview is defined in control template. How can I access it?

Posts

  • JGoldbergerJGoldberger USMember, Forum Administrator, Xamarin Team, University Xamurai
    edited June 2018

    @Mikilll

    You will have to go into the Children of the ContentView that is displaying the ControlTemplate with the ScrollView.

    ControlTemplate:

    <ControlTemplate x:Key="ScrollViewTemplate">
        <ScrollView>
               ...
        </ScrollView>
    </ControlTemplate>
    

    ContentView:

    <ContentView x:Name="scrollViewParent" ControlTemplate="{StaticResource ScrollViewTemplate}" >
    </ContentView>
    

    In Code behind:

    var scrollView = scrollViewParent.Children[0] as ScrollView;
    await scrollView?.ScrollToAsync(x, y, true);
    

    Of course you will have to modify based on the layout you have set up in the ControlTemplate and the ContentView displaying it, but if the ScrollView is the first child of the ContentView then the above should work.

  • AndreiMisiukevich_AndreiMisiukevich_ USMember ✭✭✭✭✭
    edited June 2018
    var scrollView = scrollViewParent.Children[0] as ScrollView;
    await scrollView?.ScrollToAsync(x, y, true);
    

    It must be

    var scrollView = scrollViewParent.Content as ScrollView;
    await scrollView?.ScrollToAsync(x, y, true);
    
Sign In or Register to comment.