Xamarin Forms - async ContentPage

I have the following content page where I want to load Steema Teechart, but I cannot because I cannot make the MainPage asynchronous:

My main page:

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 the MainPage async so that chartView.Model = await test1.GetModel();

might work? I've tried with "async MainPage" but I am getting errors.

+3


source to share


1 answer


No, you cannot. A constructor cannot be asynchronous in C # ; a 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 like



MainPage page = await MainPage.CreateMainPageAsync(true);

      

Note that I added the "Async" suffix to the method GetModel

, which is a general convention used for asynchronous methods.

+7


source







All Articles