Search code examples
c#formsxamarinpositionvisible

Xamarin Forms - Recognize Postition


I want to make a comment entry that is only visible if the user is at the bottom of the article. So the app has to recognize when the user has scrolled enough, then a method should make the entryfield visible.

I can't find something like this on the Internet, so maybe you guys can help me.

This one is without the entryfield and when the user scrolls down ...

... the entryfield becomes visible


Solution

  • If you are using a ScollView, there is a Scrolled event that fires whenever the view is scrolled and the ScrolledEventArgs contain ScrollX and ScrollY properties that allow you to know where the ScrollView currently is. If you compare ScrollY to the height of the ContentSize property of the ScrollView, e.g.:

    XAML:

    <StackLayout>
        <ScrollView x:Name="scrollView" Scrolled="Handle_Scrolled">
            <StackLayout>
                <Label Text="{Binding Article}" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand" />
            </StackLayout>
        </ScrollView>
        <Entry IsVisible="{Binding AtEnd}" Placeholder="End reached!" />
    </StackLayout>
    

    Code behind (MainPage is a ContentPage subclass):

    string _article;
    public string Article
    {
        get
        {
            return _article;
        }
        set
        {
            if (_article != value)
            {
                _article = value;
                OnPropertyChanged("Article");
            }
        }
    }
    
    bool atEnd;
    public bool AtEnd
    {
        get
        {
            return atEnd;
        }
        set
        {
            if (atEnd != value)
            {
                atEnd = value;
                OnPropertyChanged("AtEnd");
            }
        }
    }
    
    public MainPage()
    {
        Article = "<put in enough text here to force scrolling>";
        AtEnd = false;
        InitializeComponent();
        BindingContext = this;
    }
    
    void Handle_Scrolled(object sender, Xamarin.Forms.ScrolledEventArgs e)
    {
        if (e.ScrollY + scrollView.Height >= scrollView.ContentSize.Height)
            AtEnd = true;
        else
            AtEnd = false;
    }
    

    That said, why not just put the entry below the article using the same scroll view? IOW just put the Entry element after the Label above in the same StackLayout and the Entry will just be there at the end always, but the user won't see it until they scroll down. Seems that that would be a simpler solution. Of course you may not be using a Label but the same applies, just put the Entry at the bottom of the layout that the ScrollView is scrolling.