I'm just getting started with the MVVM pattern in WPF and I decided that the most elegant way to structure my code was injecting the view-model in to the view's constructor.
This is all well and good, but ReSharper gives a warning in the XAML that my view doesn't have a default constructor. I'm assuming that this is so that I can construct my view in XAML if required, but that's only a guess.
What am I giving up by requiring my view to take a view-model in the constructor?
Edit: My view constructor looks like this:
public ExampleView(ExampleViewModel viewModel)
{
if (viewModel == null) throw new ArgumentNullException("viewModel");
DataContext = viewModel;
}
Answer: I settled on the following set up, where the DesignTime namespace contains mocked up versions of the ViewModel for testing and design time support.
ExampleView.xaml.cs
public ExampleView()
{
InitializeComponent();
}
public ExampleView(IExampleViewModel viewModel)
: this()
{
DataContext = viewModel;
}
ExampleView.xaml
<UserControl
x:Class="Wpf.Examples.ExampleView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:DesignTime="clr-namespace:Wpf.Examples.DesignTime">
<UserControl.DataContext>
<DesignTime:ExampleViewModel/>
</UserControl.DataContext>
</UserControl>