Ilia Stoilov
Ilia Stoilov

Reputation: 632

Xamarin Forms - async ContentPage

I have the following content page in which I want to load a Steema Teechart, but I can't, because I can't make the MainPage async:

My MainPage:

public class MainPage : ContentPage
{
    public MainPage (bool chart)
    {           
        ChartView chartView = new ChartView 
        { 
            VerticalOptions = LayoutOptions.FillAndExpand, 
            HorizontalOptions = LayoutOptions.FillAndExpand,
            HeightRequest = 300,
            WidthRequest = 400
        }; 

        LineModel test1 = new LineModel();
        chartView.Model = await test1.GetModel(); 

        //put the chartView in a grid and other stuff

        Content = new StackLayout { 
            HorizontalOptions = LayoutOptions.FillAndExpand,
            VerticalOptions = LayoutOptions.FillAndExpand,
            Children = {
                    grid
            }
        };
    }
}

My LineModel Class:

public class LineModel
{
        public async Task<Steema.TeeChart.Chart> GetModel ()
        { //some stuff happens here }
}

How can I make MainPage async so chartView.Model = await test1.GetModel(); can work? I've tried with "async MainPage" but I get errors.

Upvotes: 3

Views: 2059

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73452

No you can't. Constructor can't be async in C#; typical workaround is to use an asynchronous factory method.

public class MainPage : ContentPage
{
    public MainPage (bool chart)
    {           
        ChartView chartView = new ChartView 
        { 
            VerticalOptions = LayoutOptions.FillAndExpand, 
            HorizontalOptions = LayoutOptions.FillAndExpand,
            HeightRequest = 300,
            WidthRequest = 400
        };    
    }

    public static async Task<MainPage> CreateMainPageAsync(bool chart)
    {
         MainPage page = new MainPage();

        LineModel test1 = new LineModel();
        chartView.Model = await test1.GetModelAsync(); 
        page.Content = whatever;

        return page;
    }
}

Then use it as

MainPage page = await MainPage.CreateMainPageAsync(true);

Note that I've added "Async" suffix to the method GetModel which is the general convention used for asynchronous methods.

Upvotes: 10

Related Questions