views:

38

answers:

2

Hello,

how can I datatemplate a UserControl with a ViewModel with a NON-Empty constructor ?

public PersonViewModel(Person person)
  {
     _person= person;
       // do some stuff                          
  }

Binding this in Xaml will crash as the Ctor is not empty. But as I use parent/child relations with the ViewModels I have to pass the person object to the constructor of the ViewModel...

How do you cope with that situation?

A: 
 var person = new Person();
 var viewModel = new PersonViewModel(person);

 var view = new EditPersonView(viewModel); // use overloaded constructor to inject DataContext
 // OR
 var view = new EditPersonView{ DataContext = viewModel };

If you really want to instantiate the view-model in XAML, then you need to expose a public Person Person property and stick with the parameterless constructor. Just do in the Person setter what you would have done in the constructor. Of course, now you have opened a can of worms because you'll also need to instantiate the Person in XAML with a parameterless constructor and soon things get very ugly…

Jay
@Jay as you say ugly... no solution in sight :/
Lisa
@Lisa May I ask why you want to instantiate the view-model from the XAML? This is what makes things messy.
Jay
because I find this useful:................................ <DataTemplate DataType="{x:Type ViewModel:CustomerViewModel}"> <View:CustomerUserControl/> </DataTemplate>
Lisa
A: 

Hi

You may use Setter based injection of person in PersonViewModel.

so Simply create a property in your view model

public class PersonViewModel

{

public PersonViewModel() {};

private Person _person = default(Person);

public Person MyPerson

{

 get 

  {
    if(_person==null)
        _person=new Person();
     return _person;

  }

 set

  {
     _person =value;
  }

} }

and from your client code you can set this dependency..

kindly read more at Dependency Injection at

http://martinfowler.com/articles/injection.html

saurabh