I have Resharper on my Visual Studio, so setting the DataContext in a WPF xaml file is very useful to get to the IntelliSense. Something like this:
<UserControl ... blah blah namespace stuff >
<UserControl.DataContext>
<viewModels:FooViewModel />
</UserControl.DataContext>
<Label Text={Binding SomeText} /> <!-- I can get IntelliSense for SomeText -->
...
However, I want to do a bit of initialisation on the ViewModel/DataContext before I give it to the view. Something like this:
public class FooViewModel : INotifyPropertyChanged {
private Foo Model { get; set; }
public FooViewModel(Foo model) {
Model = model;
}
// Only here for WPF compatibility - I realise this might be the root of my problems :)
public FooViewModel()
: this (new Foo) {
}
public string SomeText { ... }
...
}
public class ShowFooer {
public void ShowFoo() {
Foo model = ... // get the foo from where ever
FooViewModel viewModel = new FooViewModel(model);
FooWindow window = new FooWindow(viewModel); // Push the data context into the constructor
view.Show();
...
}
}
When I debug through this I find that 2 FooViewModel
s are created - one where I push the context into the constructor, and one that is automatically created in the InitialiseComponents
of the FooWindow
.
tl;dr: Is there a way to say to WPF that I already have a data context and that I am just using the data context xaml tag to get IntelliSense? Is there a way from stopping it creating a new context? At the moment I am just commenting out the data context lines when I compile and uncomment them when I am coding.
Or alternative question: Is there a way to set the data context after the constructor, but have all the fields initialised from the second data context without having to do a long list of OnPropertyChanged
calls?