Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTemplate a ViewModel with a NON-Empty Constructor ?

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?

like image 915
Elisabeth Avatar asked Nov 15 '22 07:11

Elisabeth


1 Answers

 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…

like image 91
Jay Avatar answered Dec 16 '22 04:12

Jay