应将数据加载到ViewModel中的哪个位置

时间:2017-08-04 18:12:45

标签: c# android ios xamarin mvvm

我正在使用 Xamarin.Forms ,并希望调用异步方法将数据加载到视图模型中。

如何将数据(异步)加载到视图模型中?

我尝试在构造函数中执行此操作,但我无法在构造函数中调用async方法。

这是我的代码:

public List<IdeaResource> IdeasList;
public IdeasViewModel()
{
    HypermediaClient client = new HypermediaClient();
    IdeasList = await client.GetIdeasAsync();
}

1 个答案:

答案 0 :(得分:1)

While definitely not a best practice there is a work around. Create an event and call the event from the constructor.

The work around is that the event handler can be async and calling the event wont block the UI thread.

public class IdeasViewModel : ViewModelBase {
    public List<IdeaResource> IdeasList;
    public IdeasViewModel() {
        Initialized += OnInitialized;
        Initialized(this, EventArgs.Empty);
    }

    private event EventHandler Initialized = delegate { };

    private async void OnInitialized(object sender, EventArgs e) {
        //unsubscribing from the event
        Initialized += OnInitialized;
        //call async 
        var client = new HypermediaClient();
        IdeasList = await client.GetIdeasAsync();   
    }
}

Ideally the data load functionality should be in a publicly available method

public async Task LoadDataAsync() {
    var client = new HypermediaClient();
    IdeasList = await client.GetIdeasAsync();  
}

and called in an event handler in the view.

public class IdeasPage : ContentPage {
    private IdeasViewModel viewModel;

    public IdeasPage() {
        //...assign variables
    }

    protected override void OnAppearing() {
        this.Appearing += Page_Appearing;
    }

    private async void Page_Appearing(object sender, EventArgs e) {
        //...call async code here
        await viewModel.LoadDataAsync();

        //unsubscribing from the event
        this.Appearing -= Page_Appearing;
    }
}