使用MVVM从WPF ListView项触发双击事件

在使用MVVM的WPF应用程序中,我有一个带listview项的usercontrol。在运行时,它将使用数据绑定将对象集合填充到列表视图中。

将双击事件附加到列表视图中的项目的正确方法是什么,以便双击列表视图中的项目时,将触发视图模型中的相应事件并具有对被单击项目的引用?

如何以干净的MVVM方式完成操作,即视图中没有任何代码?


慕少森
浏览 1671回答 3
3回答

慕标5832272

我能够使它与.NET 4.5一起使用。看起来很简单,不需要任何第三方或代码。<ListView ItemsSource="{Binding Data}">&nbsp; &nbsp; &nbsp; &nbsp; <ListView.ItemsPanel>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ItemsPanelTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <StackPanel Orientation="Horizontal"/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </ItemsPanelTemplate>&nbsp; &nbsp; &nbsp; &nbsp; </ListView.ItemsPanel>&nbsp; &nbsp; &nbsp; &nbsp; <ListView.ItemTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <DataTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Grid Margin="2">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Grid.InputBindings>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <MouseBinding Gesture="LeftDoubleClick" Command="{Binding ShowDetailCommand}"/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Grid.InputBindings>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Grid.RowDefinitions>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <RowDefinition/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <RowDefinition/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Grid.RowDefinitions>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Image Source="..\images\48.png" Width="48" Height="48"/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <TextBlock Grid.Row="1" Text="{Binding Name}" />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Grid>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </DataTemplate>&nbsp; &nbsp; &nbsp; &nbsp; </ListView.ItemTemplate>&nbsp; &nbsp; </ListView>

一只萌萌小番薯

我喜欢使用“ 附加命令行为和命令”。Marlon Grech很好地实现了“附加命令行为”。然后,可以使用这些样式为ListView的ItemContainerStyle属性分配一种样式,该样式将为每个ListViewItem设置命令。在这里,我们设置要在MouseDoubleClick事件上触发的命令,而CommandParameter将是我们单击的数据对象。在这里,我将沿着可视化树前进以获取我正在使用的命令,但是您可以轻松地创建应用程序范围的命令。<Style x:Key="Local_OpenEntityStyle"&nbsp; &nbsp; &nbsp; &nbsp;TargetType="{x:Type ListViewItem}">&nbsp; &nbsp; <Setter Property="acb:CommandBehavior.Event"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Value="MouseDoubleClick" />&nbsp; &nbsp; <Setter Property="acb:CommandBehavior.Command"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Value="{Binding ElementName=uiEntityListDisplay, Path=DataContext.OpenEntityCommand}" />&nbsp; &nbsp; <Setter Property="acb:CommandBehavior.CommandParameter"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Value="{Binding}" /></Style>对于命令,您可以直接实现ICommand,也可以使用MVVM Toolkit中提供的一些帮助程序。
打开App,查看更多内容
随时随地看视频慕课网APP