0
votes

Am trying to load ItemSource of a picker when the picker is focused. But the data is not loaded on 1st focus.

here is the code sample

List<object> itmSrc;

Picker picker = new Picker();
itmSrc = Controls[i].ItemSource;
picker.Focused += BindItemSourceOnFocus;

public void BindItemSourceOnFocus(object sender, FocusEventArgs e)
{
    var p = e.VisualElement as Picker;
    p.ItemsSource = itmSrc;
}

If any other different approach is possible, let me know.

1
Why you need to bind on focus? Isn't better to do it on page loaded?FabriBertani
@FabriBertani It is to reduce the time takes to render the page.Mohammed Ameen
Best practice is to do all that kind of things on page load, if your page takes too long to render the page check the amount of layouts that you're using and how they affect the renderer time.FabriBertani
If the time to load is the issue, you can use an async method to load the picker data. Actually, I guess your code is working, but the list you see at the first time is the empty one, that opens 'together' the focus event is being thrownDiego Rafael Souza
@DiegoRafaelSouza yes you are right that's what happens. Can you show me some sample snippet how this can be achieved.Mohammed Ameen

1 Answers

0
votes

You can do it adding items on an async method, or another thread. Load the data on view focus is just transferring the issue to another place, and it gives a bad user experience at all.

If you run a code block inside a Task.Run(), for example, this code will be executed on another thread, and the interface should not hang on data loading.

Something like this:

public class MyPage : ContentPage
{
    List<object> itmSrc;
    Picker picker;

    public MyPage()
    {
        // Your stuff goes here
        itmSrc = new List<object>();

        picker = new Picker();
        StackLayout content = new StackLayout();

        content.Crindren.Add(picker);

        this.Content = content;

        Task.Run(() => LoadData());
    }

    private void LoadData()
    {
        // Get your data from anywhere and put it on the itemSrc from here.
        // Then...

        picker.ItemsSource = itmSrc;
    }
}

I hope it helps.