Home > Software engineering >  WPF - MVVM - How does the ViewModel set its Properties?
WPF - MVVM - How does the ViewModel set its Properties?

Time:07-02

My question is, where exactly do I call my "GetBookInformation()" Method and assign its return value to the ViewModel Property "Books"? Do I do all of this inside of the ViewModel constructor or do I do call the method inside of the view class and hand over the return value as an argument to the constructor of the ViewModel?

I have the following ViewModel Class:

public class MainWindowViewModel
{
    public List<BookInformation> Books { get; set; }

    public MainWindowViewModel()
    {
     // ?
    }
}

this is my view:

public partial class MainWindow : Window
{
    private readonly MainWindowViewModel viewModel;
    public MainWindow()
    {
        InitializeComponent();

        viewModel = new MainWindowViewModel();
        DataContext = viewModel;
    }
}

and this is my model:

internal class Query
{
    public List<BookInformation> GetBookInformationData()
    {
        return new List<BookInformation>()
        {
            new BookInformation("Undying Love", "Lex Luthor"),
            new BookInformation("The Beauty and the Beast", "Frank Downer"),
            new BookInformation("Harry Potter and the ghost of christmas", "Caroline Wood")
        };
    }

    //More Data Querys
}

CodePudding user response:

My understanding is that your View shouldn't "know" anything about underlying data sources. Just how to display them. I suggest doing it like this (in VM):

public List<BookInformation> Books 
{ 
   get { return new Query().GetBookInformationData(); }
}

or

public List<BookInformation> Books => new Query().GetBookInformationData();

if you don't store your Query class anywhere. Otherwise replace "new Query()" with your object. There is no need for a setter if there is only one source. When your View binds to this property, it will automatically call relevant method.

  • Related