If I use this construction of view. How do I pass some data to the DataEditViewModel
?
<Window x:Class="DataEditView">
<Window.DataContext>
<local:DataEditViewModel />
</Window.DataContext>
<Grid>
<!-- ... -->
</Grid>
</Window>
In some other viewmodel I can call something something like this:
public void EditCommandExecute() {
var edit = new DataEditViewModel(this._data);
edit.Show();
}
and then in DataEditView
constructor in code behind:
public DataEditView(DataObjectTm dt){
InitializeComponent();
DataContext = new DataEditViewModel(dt);
}
My solution works, but then I have duplicate code, once I setup DataContext
in XAML and then in code behind.
If you need parameters for your View Model Constructor, then you are going to have to use some type of dependency injection, and a service to pass data to the ViewModel if you wish to keep Design time data separate from runTime data Secondly, opening a view from the view model is really bad for testing, because in unit testing your ViewModel, it is going to actually open up a window, which is not what you want.
I would recommend you look into some kind of IOC container. MVVM-Light has a very simple one, but it takes some work to understand what it does and how you want to use it. That would be my recommendation for a start.
Using this you can create a Design Time and Run Time interface, and when in RunTime you pass your correct data (probably from a DB), and in design time you send static data. And also, when testing, you will not open Views, you will just check that the call to open the view was sent and received. Hope that helps somewhat.
Here is an example of how I do this Best Way to Pass Data to new ViewModel when it is initiated