Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass OnAppearing to a ViewModel in Xamarin Forms MVVM?

I have business logic that loops around and does waits and other things. Currently this is in the code behind.

From what I have been able to read this is the wrong place and I should be placing this in the viewModel (correct me if wrong). If that's the case then should I have an OnAppearing method in my VM and if so how should I pass the OnAppearing to the View Model?

Currently my page OnAppearing looks like this:

    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;

If I am to be moving most of the business logic to the ViewModel then would that mean that all of this would move to an OnAppearing() method I create in the ViewModel?

like image 828
Alan2 Avatar asked Mar 04 '23 18:03

Alan2


1 Answers

Other way is using Behaviors.Forms from David Britch

    ...
    <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>
    ...

Original

Or Xamarin Community Toolkit EventToCommandBehavior

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

Related Question: EventHandlerBehavior vs EventToCommandBehavior

like image 162
Diego Venâncio Avatar answered May 10 '23 20:05

Diego Venâncio