2011-05-25 193 views
2

我一直在使用Silverlight中的MVVM模式,並且想知道如何在ViewModel構造函數具有參數(如果接口類型)時從View實現到ViewModel的綁定。MVVM ViewModel默認構造函數

如果我將視圖模型綁定到XAML中的視圖,那麼您不能使用參數化的構造函數。鑑於我正在創建一個默認構造函數,將實例傳遞給參數化的構造函數,但是這打破了抽象。

查看

<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> 

視圖模型

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 

什麼是解決這個問題的方法?建議使用視圖背後的代碼傳入參數化構造函數,然後綁定到視圖模型?

+0

有2個縮小器不起作用?你使用mvvm燈嗎? – 2011-05-25 12:31:07

+0

是的,我正在使用MVVMLight。這兩個構造函數確實有效,但它通過從默認構造函數傳遞具體實現來打破視圖模型的抽象。 – 2011-05-25 20:09:08

+0

你爲什麼不與ViewModelLocator綁定? – 2011-05-25 20:46:06

回答

1

您可以使用IoC容器來創建對象,包括視圖和視圖模型。當這樣做時,如果可能的話,容器將嘗試通過視圖模型滿足所有需要的組件。