Call a CodeBehind Method from ViewModel

Viewed 398

i am trying to learn the MVVM design pattern by coding a little App using Xamarin.Forms. I safe all the data in the Android File-System (XML) to make it persistent. But at the moment all the methods to safe the Data are in the ViewModel and i am trying to move those Methods to the CodeBehind (Model) in order to respect the MVVM design pattern.

After i moved all the Methods to the CodeBehind i am not able to call the functions within my ViewModel even though they are within the same namespace and declared as public.

The Method DeleteCar(...) within my ViewModel tries to call the method ToCarsFile(...) which is in CodeBehind:

public void DeleteCar(object sender)
{
    AllCars.Remove(sender as Car);
    ToCarsFile(AllCars); //This is underlined in red
}

CodeBehind (.xaml.cs):

public void ToCarsFile(ObservableCollection<Car> CarsList)
{
    --SOME CODE FOR DATA PERSISTENCE--
}

I get the error "Error CS0103: The name 'ToCarsFile' does not exist in the current context (CS0103) (ProjectCars)"

Probably a stupid mistake but what am i doing wrong?

1 Answers

Lots of things going on here:

1st. Since functions are declared in classes, then you need an instance of the class to call it

public class SomeModel {
    public void ToCarsFile(ObservableCollection<Car> CarsList)
    {
    --SOME CODE FOR DATA PERSISTENCE--
    }
}

So to call it, you need something like this

   var modelObject = new SomeModel();
   modelObject.ToCarsFile(/*data*/);
  1. Your xaml.cs should not be your model. Both ViewModel and Model should be independent from the view (the xaml.cs class is your view class)

So there is something in your MVVM wiring that needs some refining

Related