【发布时间】:2011-05-25 10:30:25
【问题描述】:
我一直在了解 Silverlight 中的 MVVM 模式,并且想知道当 ViewModel 构造函数具有接口类型的参数时,如何实现从 View 到 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
解决这个问题的方法是什么?是否建议使用视图背后的代码传递给参数化的构造函数,然后绑定到视图模型?
【问题讨论】:
-
拥有 2 个收缩器不起作用?你在使用 mvvm light 吗?
-
是的,我正在使用 MVVMLight。这两个构造函数确实有效,但它通过从默认构造函数传递具体实现来破坏视图模型的抽象。
-
为什么不绑定 ViewModelLocator?
-
另外,什么是 serviceDataAgent?是否需要传递,它是 RIA 服务的上下文吗?
-
@Derek :我还没有研究 ViewModelLocator 模式。 serviceDataAgent 是通过 IoC 传递适当的 concreate 实现的 RIA 服务的抽象。
标签: c# .net vb.net silverlight-4.0 mvvm