allencoded allencoded - 2 months ago 41
Android Question

Convert type Android Fragment to MvxFragment

I am updating our code base to the latest MVVMCross. I am having trouble with an error that reads:

Error CS0030: Cannot convert type `Android.Support.V4.App.Fragment' to `MvvmCross.Droid.FullFragging.Fragments.MvxFragment' (CS0030) (QualBoard.Mobile.Droid)


Code:

public override Fragment GetItem(int position)
{
var frag = Fragments.ElementAt(position);

var fragment = Fragment.Instantiate(_context,
FragmentJavaName(frag.FragmentType));
((MvxFragment)fragment).DataContext = frag.ViewModel;
return fragment;
}


The problem child line is:
((MvxFragment)fragment).DataContext = frag.ViewModel;


I am having trouble putting together what I should use in MVVMCross version 4 in replace of what was used previously.

Answer

I believe the issue is you are casting to the wrong MvxFragment class type.

Mvvmcross offer two MvxFragment class type to match those offered in Android:

Error CS0030: Cannot convert type Android.Support.V4.App.Fragment to MvvmCross.Droid.FullFragging.Fragments.MvxFragment

By the looks of your error I would say that you are using fragments from the support libraries and therefore should rather use MvvmCross.Droid.Support.V4.MvxFragment.