首页 > 解决方案 > 将 OnAppearing 传递给 Xamarin Forms MVVM 中的 ViewModel?

问题描述

我有业务逻辑循环并执行等待和其他事情。目前这在后面的代码中。

据我所知,这是错误的地方,我应该把它放在 viewModel 中(如果错了,请纠正我)。如果是这种情况,那么我是否应该在我的 VM 中有一个 OnAppearing 方法,如果是这样,我应该如何将 OnAppearing 传递给视图模型?

目前我的页面 OnAppearing 看起来像这样:

    protected async override void OnAppearing()
    {
        base.OnAppearing();
        Title = Settings.mode.Text() + " Deck";
        vm.LearnViewVisible = Settings.mode.IsLearn();
        vm.PracticeViewVisible = Settings.mode.IsPractice();
        vm.QuizViewVisible = Settings.mode.IsQuiz();
        vm.QuizStartViewVisible = false;

如果我要将大部分业务逻辑移至 ViewModel,那么这是否意味着所有这些都将移至我在 ViewModel 中创建的 OnAppearing() 方法?

标签: xamarinxamarin.forms

解决方案


另一种方法是使用David Brich的 Behaviors.Forms

    ...
    <ContentPage.Behaviors>
        <behaviors:EventHandlerBehavior EventName="Appearing">
            <behaviors:InvokeCommandAction Command="{Binding PageAppearingCommand}" />
        </behaviors:EventHandlerBehavior>
        <behaviors:EventHandlerBehavior EventName="Disappearing">
            <behaviors:InvokeCommandAction Command="{Binding PageDisappearingCommand}" />
        </behaviors:EventHandlerBehavior>
    </ContentPage.Behaviors>
    ...

原来的

Xamarin 社区工具包 EventToCommandBehavior

    <ContentPage.Behaviors>
            <xct:EventToCommandBehavior
                EventName="Appearing"
                Command="{Binding PageAppearingCommand}" />
            <xct:EventToCommandBehavior
                EventName="Disappearing"
                Command="{Binding PageDisappearingCommand}" />
    </ContentPage.Behaviors>

相关问题:EventHandlerBehavior 与 EventToCommandBehavior


推荐阅读