I have a ViewModel called QViewModel and it extends ViewModelBase. In the QViewModel class I call ToNext() method from ViewModelBase as shown below. What I want to do is, to pass Another view model class called VMTest which is also extends ViewModelBase, and then start VMTest in ViewModelBase class as shown in the code below.
As shown in the body of ToNext() in the ViewModelBase class, I am trying to start the ViewModel class I passed from the QViewModel „VMTest“ by using ShowViewModel(), but I get the following error:
viewModel is a variable but used as a type
Please let me know how to call ShowViewModel() correctly to start the VMTest viewModel
code:
//In QViewModel
ToNext(new MvxViewModelRequest< VMTest>);
//In ViewModelBase
public void ToNext(MvxViewModelRequest<ViewModelBase> vm)
{
if (vm.ViewModelType.Name == typeof(ViewModelBase).Name {
var viewModelLoader = Mvx.Resolve<IMvxViewModelLoader>();
var viewModel = viewModelLoader.LoadViewModel(vm, null);
ShowViewModel<viewModel>();
}
ShowViewModel<T>
is a generic method. When using a generic method, you need to pass in the "Type parameter" into the angle brackets (< >). The Type parameter is simply the name of the class. For example, List<T>
is a generic type. If you want to create a List of strings, you would write:
List<string> strList = new List<string>();
In the code you posted, you are calling ShowViewModel<T>
but instead of passing in a Type parameter, you are passing in a locally defined variable: viewModel
. It's equivalent to doing this:
var str = "test";
List<str> strList = new List<str>(); //this will throw an error because str is a variable not a type parameter
In order to fix this issue, you can modify your code as such:
//In QViewModel
ToNext<VmTest>();
//In ViewModelBase
public void ToNext<T>() where T : ViewModelBase
{
ShowViewModel<T>();
}
The ToNext
method is changed to a generic method that takes a type parameter called "T". The where T : ViewModelBase
is called a "Type Constraint" and it tells the compiler that any Type parameter passed to the ToNext method must inherit from ViewModelBase. Calling ToNext() with a parameter that does not inherit from ViewModelBase will cause a compile error.
The following two lines have been removed:
var viewModelLoader = Mvx.Resolve<IMvxViewModelLoader>();
var viewModel = viewModelLoader.LoadViewModel(vm, null);
MvvmCross will do this for you internally when you call ShowViewModel. So you don't need to do it yourself.
Hope it helps!