Kam
Kam

Reputation: 391

Mvvm Cross Navigation throughout fragments

I cannot bind the click event from layout to ViewModel.

I want to make a navigation throughout two fragments with MVVM Cross 5.6. I am using native Xamarin.Android.

First, I created a ViewModel:

public class FirstFragmentViewModel : MvxViewModel
{
   public ICommand NavigateCommand => new MvxCommand(() => { 
     this.ShowViewModel<ProfileFragmentViewModel>(); });
}

The used layout is:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:background="#005000"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Navigate"
        local:MvxBind="Click NavigateCommand"
        android:background="#ffec4747"
        android:clickable="true"/>
</LinearLayout>

Then, I created a Fragment:

public class FirstFragmentView : MvxFragment<FirstFragmentViewModel>
{
   public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
   {
        base.OnCreateView(inflater, container, savedInstanceState);
        return this.BindingInflate(Resource.Layout.FirstFragmentView, null);
   }
}

The FirstFragmentView is initailized here:

[Activity(MainLauncher = true)]
public class TabView : MvxTabsFragmentActivity
{
    public TabView()
        : base(Resource.Layout.Home, Resource.Id.actualtabcontent)
    {
    }

    public FirstFragmentViewModel FirstViewModel => (FirstFragmentViewModel)this.ViewModel;
    public FirstViewModel SecondViewModel => (FirstViewModel)this.ViewModel;

    protected override void AddTabs(Bundle args)
    {
        AddTab<FirstFragmentView>("1", "Tab 1", args, FirstViewModel);
        AddTab<SecondFragmentView>("2", "Tab 2", args, SecondViewModel);
    }

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
    }
}

The button is displayed but it is in disabled state and clicking it, nothing happens.

Upvotes: 0

Views: 858

Answers (1)

pnavk
pnavk

Reputation: 4630

It looks like you are passing in the wrong ViewModel when you call:

AddTab<FirstFragmentView>("1", "Tab 1", args, FirstViewModel);

The following lines in you Activity look suspicious:

public FirstFragmentViewModel FirstViewModel => (FirstFragmentViewModel)this.ViewModel;
public FirstViewModel SecondViewModel => (FirstViewModel)this.ViewModel

You are casting this.ViewModel to both FirstFragmentViewModel and FirstViewModel, which doesn't make sense. The Activity and each of the Fragments should have their own separate ViewModels.

Try making this change and see if it works:

 AddTab<FirstFragmentView>("1", "Tab 1", args, new FirstFragmentViewModel());

Upvotes: 1

Related Questions