Forum Xamarin.Forms

How to pass the parameter in ViewModel from the page (view) following the MVVM model?

dcpartnersdcpartners Member ✭✭
edited October 2019 in Xamarin.Forms

Hi there

I'm starting to move/transfer the code from event-driven into MVVM. At this stage, I'm not prepared yet to follow the frameworks such as Prism or LightMVVM etc as yet as some codes still in event-driven and some already in MVVM.

I have a CRUD application (list, detail including add/edit). I started to use Unity container and register dependency injection.

My question as follow:

In my List page/view with ListViewModel, once clicked (selectedItem) it will pass the Id into detail page as follow:

await _navigation.PushAsync(new ActivityDetailPage(selectedActivityId));

On the view (DetailPage):

public ActivityDetailPage(int activityId)
    InitializeComponent ();
    BindingContext = ServiceLocator.Current.GetInstance<ActivityDetailViewModel> ();

My app.xaml.cs:

 public App()
            var unityContainer = new UnityContainer();
            unityContainer.RegisterType<IActivityService, ActivityApiService>();

            ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(unityContainer));

            if (!string.IsNullOrEmpty(Preferences.Get(Constant.Setting_AccessToken, "")))
                MainPage = new MasterPage();
            else if (string.IsNullOrEmpty(Preferences.Get(Constant.Setting_UserEmail, "")) && 
                string.IsNullOrEmpty(Preferences.Get(Constant.Setting_Password, "")))
                MainPage = new NavigationPage(new LoginPage());


How do I pass the Id into this? Also how do I pass INavigation into this?



  • MehdiMllMehdiMll Member ✭✭

    Can you use a behaviorListView

    `public class ListViewBehavior : Behavior
    ListView listView;
    protected override void OnAttachedTo(ListView bindable)

            listView = bindable;
            listView.ItemSelected += ListView_ItemSelected;
        void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
            MyModel selectedItem = ((ListView)sender).SelectedItem as MyModel;
            if (selectedItem  == null)
                ((ListView)sender).SelectedItem = null;
                 await _navigation.PushAsync(new ActivityDetailPage(selectedItem.selectedActivityId));
                ((ListView)sender).SelectedItem = null;
        protected override void OnDetachingFrom(ListView bindable)
            listView.ItemSelected -= ListView_ItemSelected;


    and in your CTOR :

    public ActivityDetailPage(int Id) { BindingContext =ActivityDetailViewModel(Id); }

  • ColeXColeX Member, Xamarin Team Xamurai

    @dcpartners Hi , Any update ?

Sign In or Register to comment.