【问题标题】:What is the standard convention for defining nested view:viewmodel mapping in MVVM Light定义嵌套视图的标准约定是什么:MVVM Light 中的视图模型映射
【发布时间】:2011-02-09 07:28:38
【问题描述】:

所以在我见过的经典 MVVM 示例中,DataTemplate 定义用于将视图模型映射到视图,在 MVVM Light 框架中执行此操作的标准方法是什么,映射应该位于哪里?以下是我现在正在做的和我正在谈论的示例,可混合性对我来说很重要!

主窗口:

<Window 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" 
        x:Class="STS2Editor.MainWindow"
        Title="{Binding ApplicationTitle, Mode=OneWay}"
        DataContext="{Binding RootViewModel, Source={StaticResource Locator}}">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Skins/ApplicationSkin.xaml" />
                <ResourceDictionary Source="Resources/ViewMappings.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <ContentControl Content="{Binding ApplicationManagementViewModel}" HorizontalAlignment="Left" VerticalAlignment="Top"/>
    </Grid> 
</Window>

在上面的代码中,我的 RootViewModel 类有一个具有相同属性名称的 ApplicationManagementViewModel 类的实例:

public ApplicationManagementViewModel ApplicationManagementViewModel {get {...} set {...} }

我引用 ResourceDictionary“ViewMappings.xaml”来指定我的视图模型如何表示为视图。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:STS2Editor.ViewModel">
    <DataTemplate DataType="{x:Type local:ApplicationManagementViewModel}">
        <local:ApplicationManagementView/>
    </DataTemplate>
</ResourceDictionary>

我应该使用 ViewModelLocator 做这样的事情吗?视图模型的集合呢?

【问题讨论】:

  • 我意识到 MVVM 的一大问题是缺乏统一的方法。
  • 我认为这不是 MVVM 本身的问题。这是一种模式,具有多种实现。与 MVC 或其他相同。我不认为这是一个问题,这实际上取决于您要解决的情况和问题。
  • 我有非常相似的问题。那么 DataTemplates 对 WPF 来说足够好了吗?我想要一个 Prism 区域类型的东西,但没有 Prism。

标签: wpf mvvm mvvm-light blendability


【解决方案1】:

您使用的方法(使用隐式类型的 DataTemplates)在 WPF 中可以正常工作,但不幸的是它在 Silverlight 中不起作用。这就是为什么我更喜欢使用更明确的方法的原因之一。

此外,隐式类型的 DataTemplates 可能有点令人困惑,因为模板的来源并不总是很清楚。这有时会使集成商的工作变得非常困难,尤其是对于 UI 的小改动(去过那里,做到了 :)

没有义务在 MVVM Light 中使用 ViewModelLocator,它只是一种运行良好且非常容易理解的方式(对于阅读代码但不熟悉 WPF/SL 细节的人)。最后,这在很大程度上是一个偏好问题,但最近 ViewModelLocator 模式似乎越来越受欢迎(例如,参见这篇文章,其中通用 ViewModelLocator 与 MEF 一起使用)。

http://www.johnpapa.net/simple-viewmodel-locator-for-mvvm-the-patients-have-left-the-asylum/

最后,我补充一点,我对当前在 MVVM Light 中的 ViewModelLocator 实现不是很满意,我想在下一个版本中提出一个更通用的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-29
    • 2011-05-20
    • 1970-01-01
    • 2017-04-10
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多