I have been getting up to speed with the MVVM pattern in Silverlight and was wondering how to implement binding from the View to the ViewModel when the ViewModel constructor has a parameter if an interface type.
If I bind the viewmodel to the view in XAML then you can not use a parameterised constructor. Given that I was creating a default constructor passing an instance to the parameterised constructor but this breaks the abstraction.
View
<navigation:Page x:Class="QSmart.DataViewer.Report.RecentFailures.Report"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
xmlns:local="clr-namespace:QSmart.DataViewer.Report.RecentFailures"
d:DesignWidth="640" d:DesignHeight="480"
Title="Report Page" xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation">
<UserControl.Resources>
<local:ReportViewModel x:Key="ViewModel"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" DataContext="{StaticResource ViewModel}" >
<telerik:RadGridView Name="RadGridView1" ItemsSource="{Binding Path=Faults,Mode=OneWay}" AutoGenerateColumns="True" />
</Grid>
</navigation:Page>
View Model
Public Sub New(ByVal serviceDataAgent As IRecentFailuresReportServiceAgent)
If Not IsInDesignMode Then
If serviceDataAgent IsNot Nothing Then
ServiceAgent = serviceDataAgent
End If
Messenger.Default.Register(Of RecentFailuresMessage)(Me, Sub(m) ChangeReportSettings(m))
LoadData()
End If
End Sub
What is the method to get around this? Is it recommended to use the code behind of the view to pass into the parameterised constructor and then bind to the viewmodel?
You can use an IoC container to create your objects, including view and view model. When doing this, the container will try to satisfy all needed components by your view model, if possible.