Xamarin Forms - async ContentPage

本文关键字:ContentPage async Forms Xamarin | 更新日期: 2023-09-27 18:06:41

我有以下内容页,我想在其中加载一个Steema Teechart,但我不能,因为我不能使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 }
}

我如何使MainPage异步,使chartView.Model = await test1.GetModel();可以工作?我已经尝试过"async MainPage",但我得到错误。

Xamarin Forms - async ContentPage

不行。构造函数在c#中不能异步;典型的解决方法是使用异步工厂方法。

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;
    }
}

然后使用

MainPage page = await MainPage.CreateMainPageAsync(true);

请注意,我在方法GetModel中添加了"Async"后缀,这是异步方法使用的一般约定。