Abanoub Refaat
Abanoub Refaat

Reputation: 59

Xamarin forms Back Button Navigation

I'm working on a Xamarin Forms app and am using the MVVM Design. the issue is when am navigating to another page using

Shell.Current.GoToAsync()

I disable the button to prevent Creating Multiple Pages or DB Operations. but if I want to go back, I re-enable the buttons in the VM constructor, but the constructor never gets called which means the buttons are still disabled. I tried to append the // in the Page route to remove the stack thinking that when I go back it will create a new instance Page and VM, but that did not work. so can anyone help me resolving this problem. thanks in advance.

Update: VM Code

 public RegisterViewModel()
{
    Debug.WriteLine("Class Constructor", Class_Name);
    //in case if disabled
    RegisterButtonEnabled = true;            
            
    RegisterCommand = new Command(RegisterButtonOnClick);
}


    public ICommand RegisterCommand { get; }

    private bool registerButtonEnabled = true;
    public bool RegisterButtonEnabled 
    { 
        get => registerButtonEnabled;
         set 
        { 
            registerButtonEnabled = value;
             OnPropertyChanged();
        } 
    }


private async void RegisterButtonOnClick()
{

    
         RegisterButtonEnabled = false;
        //More Code
        //and then go to Register Page
         await Shell.Current.GoToAsync(nameof(RegisterPage));
    
}

and my xaml

<Button              
                Command="{Binding RegisterCommand}"
                Text="{xct:Translate Register}"
                Style="{StaticResource ButtonStyle}"
                IsEnabled="{Binding RegisterButtonEnabled,Mode=OneWay}"/>

Upvotes: 0

Views: 1075

Answers (1)

Liyun Zhang - MSFT
Liyun Zhang - MSFT

Reputation: 14469

I had create a default shell project. And find something about the viewmodel. You can add the onappear and the ondisappear method to the viewmodel. Such as:

ViewModel:

public void OnAppearing()
    {
      RegisterButtonEnabled = true;
    }
public void OnDisAppearing()
    {
      RegisterButtonEnabled = false;
    }

Page.cs

   ItemsViewModel _viewModel;

    public ItemsPage()
    {
        InitializeComponent();

        BindingContext = _viewModel = new ItemsViewModel();
    }
   protected override void OnAppearing()
    {
        base.OnAppearing();
        _viewModel.OnAppearing();
        
    }
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        _viewModel.OnDisAppearing();
    }

Upvotes: 0

Related Questions