As I understand it, when I bind my ViewModel to my View, it is done via the DataContext. Something like
<Grid.Resources>
<myData:MyVM x:Key="Vm" />
</Grid.Resources>
<Grid.DataContext>
<Binding Source="{StaticResource Vm}"></Binding>
</Grid.DataContext>
My understanding of how the ViewModel is populated is the View calls the ViewModel (via binding), and the ViewModel talks to the Model and does what ever it needs to do to get itself (ViewModel) into a desired state.
So, what happens if your “Model” is created by the UI? My model is a parameter on my MainWindow Constructor.
So, my View (MainWindow) is
public MainWindow(MyObject myObject)
{
InitializeComponent();
}
My ViewModel is
public class ViewModel
{
#region properties
private MyObject myList;
public MyObject MyList
{
get; set ;
}
#region Constructors
public ViewModel ()
{
}
public ViewModel (MyObject myObject)
{
this.myObject= myObject;
}
}
Now, when my application runs up, (and I’m sure I’m using the wrong words here) how do I ‘inject’ my parameter into the ViewModel? Or do we feel there is a better approach?
EDIT
To explain what I’m trying to achieve may help. My program performs some tasks and creates a log. The log is stored in memory. At the end of my programs processes, the log is shown on screen. This is why I’m passing the object into the constructor.
I’d rather see you bind your view to your view-model. If you are going to follow the MVVM pattern, then this is one way to do it. Now, I can’t be certain if you’re using dependency injection, but you mention “inject” in your question, so I’ll assume you are. Here’s a code sample:
SET THE DATACONTEXT OF YOUR VIEW TO YOUR VIEW-MODEL:
INJECT YOUR MODEL INTO YOUR VIEW-MODEL:
So, now your view-model is bound to your view. All model interaction should be coordinated throught the view-model.