Search code examples
mvvmcross

add fragment to activity so ViewModels of both are handled by MvvmCross


I have fragment:

[MvxFragmentPresentation(AddToBackStack = true)]
public class MyFragmentView : MvxFragment<MyFragmentViewModel>
{
...
}

This fragament is used as content in "classic NavigationDrawer UI pattern", it works ok.
Is opened by:

NavigationService.Navigate<MyFragmentViewModel>();

Additionally I want to nest above fragment in standalone Activity started with like:

NavigationService.Navigate<MyActivityViewModel>();

This activity will have additional EditTexts, TextViews etc.
Later I will develop returning result from MyActivity to caller.

How to nest Fragment in Activity so both (MyFragment and MyActivity) will have ViewModels managed by MvvmCross?

Thank you in advance!


Solution

  • You need to specify the activity which will host your fragment, as you can see in the docs you can set the ActivityHostViewModelType which is the ViewModel that is related to the Activity that will host your fragment like this:

    [MvxFragmentPresentation(AddToBackStack = true, ActivityHostViewModelType = typeof(MyActivityThatHostsTheFragmentsViewModel))]
    public class MyFragmentView : MvxFragment<MyFragmentViewViewModel>
    {
    ...
    }
    

    You can also add the id of the layout container for your fragment is needed:

    [MvxFragmentPresentation(AddToBackStack = true, ActivityHostViewModelType = typeof(MyActivityThatHostsTheFragmentsViewModel), FragmentContentId = Resource.Id.Content)]
    public class MyFragmentView : MvxFragment<MyFragmentViewViewModel>
    {
    ...
    }
    

    You can find examples on the playground of MvvmCross.

    Update:

    If you need to have the same fragment on different containers then you need to have multiple attributes, e.g. here (as you can also see you can specify different things on the attributes like if one have a fragment content id and the other doesn't)

    [MvxFragmentPresentation(AddToBackStack = true, ActivityHostViewModelType = typeof(MyActivityThatHostsTheFragmentsViewModel))]
    [MvxFragmentPresentation(ActivityHostViewModelType = typeof(OtherActivityThatHostsTheFragmentsViewModel), FragmentContentId = Resource.Id.Content)]
    public class MyFragmentView : MvxFragment<MyFragmentViewViewModel>
    {
    ...
    }
    

    HIH