c# - MVVM ViewModel 默认构造函数

标签 c# .net vb.net silverlight-4.0 mvvm

我一直在快速了解 Silverlight 中的 MVVM 模式,并且想知道当 ViewModel 构造函数具有接口(interface)类型的参数时如何实现从 View 到 ViewModel 的绑定(bind)。

如果我将 View 模型绑定(bind)到 XAML 中的 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>

查看模型

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

解决这个问题的方法是什么?是否建议使用 View 的代码隐藏传递到参数化构造函数,然后绑定(bind)到 View 模型?

最佳答案

您可以使用 IoC 容器来创建您的对象,包括 View 和 View 模型。执行此操作时,如果可能,容器将尝试满足 View 模型所需的所有组件。

关于c# - MVVM ViewModel 默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6123030/

相关文章:

c# - Asp.net core 3 Web Api post请求不起作用

c# - 设置为最大化的 WinForm 在循环中出现得太早

c# - 如何生成测试数据?

c# - 更改默认 Windows 键盘快捷键

vb.net - 多线程分组算法

c# - Automapper,按命名约定映射

c# - 如何判断一个Type是不是RunTimeType?

c# - 如何使用 Xamarin.iOS 枚举 ipv4 地址和 ipv4mask

.net - 无法将类型 'System.Byte' 的对象转换为类型 'System.Byte[]' - vb .net

vb.net - 您可以将 "type"作为参数传递吗?