question

NaveedAhmadHematmal avatar image
0 Votes"
NaveedAhmadHematmal asked NaveedAhmadHematmal commented

A function in ViewModel that executes whenever the page the ViewModel is bind to opens.

I have a code and want to execute it whenever I open that page.
I know about OnAppearing() Method in Xamarin.Forms, but it doesn't work in ViewModels. I have inherited ViewModel from ContentPage, and override the OnAppearing() Method. But When I open the page, the ViewModel doesn't execute the OnAppearing Method.

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

MichaSierpiski-9455 avatar image
2 Votes"
MichaSierpiski-9455 answered NaveedAhmadHematmal commented

Hello there.

So what I assume from the lack of code You did something like this:
public class MyViewModel : ContentPage
{
...
}
Well ContentPage is what is shown on the device, making VM inherit it is... well not a good decision.

What You what to happen is to have a method in VM be invoked everytime OnAppearing is fired in Your PAge of choise.
To do it have a public method in VM:
public class MyViewModel
{
public void MyMethod(){...}
}
and then in code behind of page:

public class MyPage : ContentPage
{
...
override void OnAppearing()
{
if(BindingContext is MyViewModel vm)
{
vm.MyMethod();
}
}

Remember that You have to have this VM as a bindingContext of the page. How to do that You should find somewhere in the documentation



}

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@MichaSierpiski-9455 Thank you! This solved my problem.

0 Votes 0 ·