【发布时间】: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.cs,ChangeTitleCommand 我想访问我单击按钮的 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