0

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.

jnovacho
  • 2,825
  • 6
  • 27
  • 44
  • What's the type of `_data`? If you can refer an instance of `_data` in `XAML` code, we can create the `DataEditViewModel` with some `_data` passed in as you want in `XAML` code – King King Nov 02 '13 at 23:35
  • In case you want to pass parameter then simply omit declaration from XAML and do this in code behind like you doing. Why to do it in XAML then? – Rohit Vats Nov 03 '13 at 09:17

1 Answers1

1

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

Community
  • 1
  • 1
Daryl Behrens
  • 643
  • 2
  • 7
  • 19