Pages

venerdì 14 dicembre 2012

Infinite Scrolling in Metro style apps/Windows Store Apps (with all this different names i'm getting confused)

I write this after two very useful days of DevCamps, where i learnt a lot of things that will be really useful in order to develop an app for Windows 8.

Most of the things that I learnt will be gradually published on the blog. the first feature that i want to talk about is an interesting way to implement the infinite scrolling inside these "Metro Style Apps"/"Store Apps"/"What-The-Hell-do-i-need-to-call-them Apps".

the "infinite scrolling" is ,for example , the way that facebook uses to load the news feed: in a first step are loaded the most recent news and when you scroll to the end of the list the list itself will grow automatically adding other news less recent...and so on.

2 things we need to do in order to achieve this in a Windows 8 app:

  • Create a class that implements "ISupportIncrementalLoading"
  • Use an instance of that class in a gridview or listview through databinding.

the interface "ISupportIncrementalLoading" got 2 things : a propery called "HasMoreItems" (that indicates if the list is completed or it needs to load other informations) and a method called "LoadMoreItemsAsync" (that executes the incremental load)


public class InfiniteScrollingCollection: ObservableCollection<YourType>, ISupportIncrementalLoading
{
    public bool HasMoreItems { get; protected set; }
    private int _page;

    public  InfiniteScrollingCollection() : base()
    {
        HasMoreItems = true;
        this._page = 0;
    }

    public async IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
    {
        return AsyncInfo.Run(async c => {
            List<YourType> data =  await LoadDataAsync(count);
            this._page++;
            foreach (var item in data) {
                Add(item);
            }

            HasMoreItems = data.Any();

            return new LoadMoreItemsResult() {
                Count = data.Count,
            };
        });
    }
    private async Task<List<YourType>> LoadDataAsync(uint count)
    {
        //load count occurrences of page "_page". 
        //i'm sorry but this step you have to do on your own.
    }

}

in this example i'm using the inheritance to the class ObservableCollection, that's because it implements all the events useful to manage the databinding in a native way.

last thing to do is to apply databinding between an instance of this class and a GridView/ListView.

Nessun commento:

Posta un commento