touyets
touyets

Reputation: 1325

WPF - MVVM start action when view is opened

I am writing a little piece of MVVM for training to wrap my head around the feature.

I have created a Model for my Image model class so that each Image item contains an ID, Name, Link and other stuff like height and width etc.

I have created a View as well to show the data. Nothing fancy. Just a simple ItemsControl that gets put inside my MainWindow Grid on startup.

I am now creating the ImageViewModel class which is where I am stumbling a little.

I have defined that class as such - not sure if I did that correctly:

public class ImageViewModel : Screen 

I have also written some code that the software should perform to go get the data from the net and just parse stuff and retrieve a new Image item for each available new item on the net. the code should work fine as it worked perfectly when i coded this without the MVVM feature.

My issue is that i do not know how to make the action (called public void FindNewImages) launch the second the View is loaded inside my MainWindow grid on startup... How can I achieve this?

Upvotes: 0

Views: 476

Answers (1)

devdigital
devdigital

Reputation: 34349

It depends on how you've wired up your view and view models. It sounds like you may be doing view first, where your view model is a resource of the view. In which case, you can invoke your FindNewImages method in the constructor of the view model.

I would however strongly recommend that you use an MVVM framework, such as Caliburn.Micro which provides screen life cycle. In this case, you could use a view model first approach, and invoke your method in the OnActivate method of the Screen type provided by Caliburn.Micro.

Upvotes: 1

Related Questions