I'm currently learning about WPF and MVVM so I've decided to create a sample application.
To my knowledge a Model is for the back end. E.g. if you have "Spaghetti" as a Model, it would have properties like "Name", "colour", "length" etc. It follows a 1:1 relationship
View Model is for the front end so the View will use what you add to the View Model. e.g. displaying a list of the different names of Spaghetti.
I'm trying to read data from the database and display all the spaghetti names to the View. I've managed to do it but I feel like I'm missing the objective of MVVM as the way I have done it does not require the Model.
Here is the code:
MainWindow.xaml.cs
public partial class MainWindow : Window
{
MainWindowSpaghettiViewModel vm = new MainWindowSpaghettiViewModel();
Service businessLogic = new Service();
public MainWindow()
{
InitializeComponent();
vm.SpaghettiNameCollection = businessLogic.GetSpaghettiNames();
DataContext = vm;
}
}
Model: Spaghetti.cs
public class Spaghetti
{
public string Name { get; set; }
public double Length { get; set; }
public string Colour { get; set; }
public decimal Price { get; set; }
}
View Model: MainWindowSpaghettiViewModel.cs
public class MainWindowSpaghettiViewModel
{
public List<string> SpaghettiNameCollection { get; set; }
}
BusinessLogic Layer: Service.cs
public class Service : IService
{
DBHelper db = new DBHelper();
public List<string> GetSpaghettiNames()
{
return db.GetSpaghettiNames();
}
}
DataAccess Layer : DBHelper.cs returns a list of spaghetti names by using a select statement.
Am I approaching this correctly as I've seen examples before where others have populated the View Model properties directly from the database?
How would the application flow? For example, in this window, I would like the user to select the name of the spaghetti they would like more information for, from the list I have just created.
After they select a spaghetti, they go to the next window where they can see all the information about the spaghetti (like the properties in the Model). Do I just create a new ViewModel with the same properties and do what I did above or do I populate the Model and then populate the ViewModel from that?