mefiX
mefiX

Reputation: 1317

Xamarin Forms MVVM with an actual model

I'm fairly new to Xamarin and stumbled across MVVM and really like it as an architectural pattern. However, I found that most HowTo's and tutorials out there only address the VVM (i.e. View-ViewModel) side of things, probably for simplicity sake!?

I would like to know how the communication between a ModelView and its associated models takes place using the INotifyPropertyChanged paradigm and other things.

If I understand correctly, I personally would put stuff like data handling, data storage (collections), db connections and stuff like that into a model. At least this is how I would've been doing it in the good old MVC days. Following questions arouse in my mind:

In my current example, I would like to implement a SensorModel which provides several sensory data which layers above can subscribe to. I would like to send updates whenever new sensor data is available to the layers above; i.e. a ViewModel, for instance.

I'd basically had something like this in mind:

class Sensor
{
    int _id { get; set; }
    string _name { get; set; }
}

class SensorModel
{
    private List<Sensor> _sensors { get; set; }
    public void addSensor(Sensor s) ...
    public void removeSensor(Sensor s) ...
}

Does anybody have links to actual/complete MVVM examples, including the connection between Model and ViewModel?

Any help appreciated.

Upvotes: 1

Views: 1518

Answers (4)

Guilherme Marques
Guilherme Marques

Reputation: 495

I would like to know how the communication between a ModelView and its associated models takes place using the INotifyPropertyChanged paradigm and other things.

I think the best way to create a communication in MVVM is Messaging Center. https://learn.microsoft.com/pt-br/xamarin/xamarin-forms/app-fundamentals/messaging-center

It's not coupled from device (sensor) code to view models ...

Your messages, in this model, active events that could acess your viewmodels as well as other structures.

A sample of this

In your view use :

public void MessegingCenterInit()
    {
        #region Bluetooth

        MessagingCenter.Subscribe<string, string>("App", "Status_name", (sender, arg) =>
        {
            App.PVM.Name = $"{arg}";//using INotifyPropertyChanged and view model
            viewmodelMethod();//using only a viewmodel
         });
        #endregion
    }

in your model use:

  public string Name
        {
            get { return name; }
            set
            {
                name = value;
                App.PVM.Add_patient.AddCanExecuteChanged();//PVM is a viewmodel
                //The view model need to have INotifyPropertyChanged as a interface
           }
        }

In specific code you have (into a generic method or event):

string new_name = John;
MessagingCenter.Send<string,string>("App","Status_name",new_name);

There are several ways to do it, its a simple one, you can try use objects as sender with less information.

Regards

Upvotes: 1

waletoye
waletoye

Reputation: 364

Use Lastest stable Xamarin Forms

MODELS

In the Project, create a Models folder

To store data, i usually use SQLite or a temp store:

class DataStore
{
    public static List<SensorModel> SensorStore { get; set; }
}

Create the SensorModel model

class SensorModel
{
    internal int Id { get; set; }
    internal string Sensor { get; set; }
}

VIEWMODELS

In the Project, create a ViewModels folder

Create a SensorVM viewmodel

class SensorVM : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public System.Windows.Input.ICommand StartCommand { get; set; }

    public string SensorName { get; set; }

    public SensorVM()
    {
        DataStore.SensorStore = new List<SensorModel>();
        StartCommand = new Xamarin.Forms.Command(StartSubmit);
    }

    private void StartSubmit(object paramter)
    {
        var sensor = new SensorModel()
        {
            Id = 1,
            Sensor = SensorName
        };

        AddSensor(sensor);
    }

    public void AddSensor(SensorModel sensor)
    {
        //do something
        DataStore.SensorStore.Add(sensor);
    }
}

VIEWS

In the Project, create a Views folder

Create a Sensor.xaml view

<ContentPage.Content>
    <StackLayout Spacing="10" Orientation="Vertical">
        <Entry Text="{Binding SensorName}"  />
        <Button Command="{Binding StartCommand}" Text="Start" />
    </StackLayout>
</ContentPage.Content>

In the code behind:

 [XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Sensor : ContentPage
{
    SensorVM vm;
    public Sensor()
    {
        InitializeComponent();

        BindingContext = vm = new SensorVM();
    }
}

Hope that helps.

Upvotes: 2

Mika
Mika

Reputation: 85

Xamarin itself gives a really good example with their default Master-Detail Solution.

Just create a new Xamarin.Forms App and select the Master-Detail Layout. It includes several Views, ViewModels (with the BaseVIewModel) and some MockUp Data Classes. For a start just have a look around there :)

Upvotes: 0

Ivan I
Ivan I

Reputation: 9990

In almost all cases there is no communication between the Model and ViewModel, and very rarely there is communication between the Model and View. If you need to communicate between Model and ViewModel it is extremely likely that you are doing something wrong.

To explain, your model usually describes some entity, like that you have the class Cat:

public class Cat
{
    public string Color {get; set;}
}

It is generally used in ViewModel either as the field or as a Collection like:

public class CatsViewModel
{
   public List<Cat> Cats {get; set;}
}

The cat shouldn't be able to update by itself, if it is updated it is done either by bindings with the view or somewhere from ViewModel.

So you have some architectural problems in your app, I think.

Upvotes: -1

Related Questions