Xamarin.Forms MVVM实现通过OnApperaing事件填充XAML ListView

时间:2016-08-10 16:51:56

标签: listview mvvm xamarin.forms

我有一个异步休息服务,可以创建一个List<>当页面通过OnAppearing事件加载时。

protected async override void OnAppearing()
{
     base.OnAppearing();

     RestService restService = new RestService();
     List<Example> exampleList = await restService.GetExample();
}

使用MVVM模式准备异步操作时,使用exampleList填充XAML ListView的最佳做法是什么?

1 个答案:

答案 0 :(得分:2)

我个人提供了一个基本的ContentPage实现,并在那里将事件指向视图模型中实现的接口。 E.G。

public interface IPageAppearingEvent
{
    void OnAppearing();
}

public class BasePage : ContentPage
{
    protected override void OnBindingContextChanged ()
    {
        base.OnBindingContextChanged ();

        var onAppearingLifeCycleEvents = BindingContext as IPageAppearingEvent;
        if (onAppearingLifeCycleEvents != null) {
            var lifecycleHandler = onAppearingLifeCycleEvents;

            base.Appearing += (object sender, EventArgs e) => lifecycleHandler.OnAppearing ();
        }
    }
}

public class ViewModel : IPageAppearingEvent
{
    public void OnAppearing()
    {
        //Do whatever you like in here
    }
}

只要您确保您的视图是BasePage的子类,那么您就可以了。