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?
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…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With