【问题标题】:Whats best practice to access Model inside Command in MVVM pattern in UWP app在 UWP 应用程序中以 MVVM 模式访问命令内部模型的最佳做法是什么
【发布时间】:2016-03-17 10:31:50
【问题描述】:

假设我在MainPage.xaml 中有一个简单的用户界面

<ListView ItemSources="{Binding Records}" ItemTemplate="{StaticResource RecordTemplate}">
</ListView>

App.xaml

<DataTemplate x:Key="RecordTemplate">
    <TextBlock Text="{Binding Title}"/>
    <Button Content="Change title" Command="{Binding DataContext.ChangeTitleCommand,
         RelativeSource={RelativeSource AncestorType=ListView}}"/>
</DataTemplate>

我想让Record类尽可能简单干净,只有一个属性Title

MainViewModel.csChangeTitleCommand 我想访问我单击按钮的 ListViewItem 的 Record 模型。

我可以通过将sender 对象转换为FrameworkElement,访问DataContext,将其转换为Record 类型并开始进行更改来做到这一点。但是它很丑,需要 ViewModel 知道 View(FrameworkElement),这使得 ViewModel 在不同的 UI 框架中不能重用,所以我想避免这种方法。

一种可能性是在 Record 类中绑定到命令,而不是在 MainViewModel 中(删除 RelativeSource={RelativeSource AncestorType=ListView}} 部分)。这样我就可以通过 this 关键字访问模型。这种方式使我的Record 类变得一团糟,因为我向RecordTemplate 添加了更多功能和事件到命令。

那么从 Command 内部访问模型的最佳做法是什么?

【问题讨论】:

    标签: c# xaml mvvm win-universal-app


    【解决方案1】:

    您可以将您的模板放到MainPage.xaml 的资源中,并设置为Command 属性如下:

    {Binding ChangeTitleCommand, Source={StaticResource ViewModelName}}. 
    

    或者您可以为您的页面设置名称并编写以下内容:

    {Binding DataContext.ChangeTitleCommand, ElementName='pagename'}
    

    【讨论】:

    • 我在我的问题中提到了这两种方法。但我的问题是如何在命令中访问模型,而不是将命令链接到正确的位置。
    • 通过“CommandParameter”属性传递。例如:Command={Binding DataContext.ChangeTitleCommand, ElementName='pagename'}, CommandParameter={Binding }
    • 如果我需要实际的事件参数,它将无法工作,因为命令仅支持 1 个参数。但我认为这种方式至少比上面的2更好。
    猜你喜欢
    • 2011-01-20
    • 2013-02-03
    • 2011-01-21
    • 2012-12-23
    • 1970-01-01
    • 2011-06-22
    • 2023-02-02
    • 1970-01-01
    • 2011-02-03
    相关资源
    最近更新 更多