Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use parameter in viewmodel ins xamarin.forms

Im trying to pass parameter to viewmodel in Xamarin.Forms.But Also I want to use it while loading the page ,to call a rest service with that parameter.But In load event parameter is null always.(I can see that parameter if I bind it to a label or etc...) How can I make it work properly and use that parameter inside the load event of viewmodel? Any help is appreciated,thanks

here is the button click event and navigate to Samplepage.

 private void OntaptedBildirimItem(string param)
    {
      this._navigationService.NavigateTo(nameof(Views.SamplePage), param);
    }

this is the Sample Page Viewmodel

      private string _id;
    public string id
    {
        get
        {
            return _id;
        }
        set
        {
            Set(() => id, ref _id, value);
        }
    }    
public SamplePageViewModel(INavigationService navigationService) : base(navigationService)
    {
        this._navigationService = navigationService;
        this.Title = "Sample Page=" + id; // here the id is always null,but if I use it to bind a label in xaml ,it has a value.
    }

This is the SamplePage Code

     public SamplePage(string parameter)
    {
        InitializeComponent();
        var viewModel = this.BindingContext as ViewModels.SamplePageViewModel;
        if(viewModel != null && parameter != null)
        {
            viewModel.bildirimid = parameter;
        }
    }
like image 372
slayer35 Avatar asked Mar 08 '23 13:03

slayer35


1 Answers

Thx for this Miguel ,this helps me a lot ,I can do what I want by this approach .You can send parameter while navigating a page in xamarin.forms like this

_navigationService.NavigateToAsync<SamplePageViewModel>("Your_parameter"); and you can get that parameter in that page's viewmodel like this

 public override async Task InitializeAsync(object yourparameter)
        {
            // use yourparameter as you wish
        }
like image 101
slayer35 Avatar answered Mar 10 '23 03:03

slayer35