【发布时间】:2017-08-14 09:55:48
【问题描述】:
我有以下 ItemsControl 来处理添加到它的项目的显示:
<ControlTemplate x:Key="MyItemsControlTemplate">
<ItemsControl x:Name="MyItemsControl" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type mynameSpace:MyClass}}, Path=ItemsSource}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<WrapPanel.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:MyCustomClass}">
<Button Command="{Binding}">
<TextBlock Text="{Binding Path=DisplayValue}"/>
</Button>
</HierarchicalDataTemplate>
</WrapPanel.Resources>
</WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ControlTemplate>
可以看到 Button 有一个 Command="{Binding}" 处理点击事件并调用命令。
现在我还想使用 ListView 来显示相同的项目并处理单击事件。我从这个链接WPF: How to bind a command to the ListBoxItem using MVVM? 看到我必须使用 Interaction.Triggers 所以我做了以下事情:
<ControlTemplate x:Key="MyListViewControlTemplate">
<ListView Name="MyListView" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type mynameSpace:MyClass}}, Path=ItemsSource}">
<ListView.View>
<GridView >
<GridViewColumn Header="Details" DisplayMemberBinding="{Binding Path=DisplayValue}"/>
</GridView>
</ListView.View>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction Command="{Binding}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListView>
</ControlTemplate>
项目在 ListView 中正确显示,因此我知道绑定对于文本显示是正确的,但我发现 ListView 的单击处理程序不会像 Button 对象那样触发命令。
有什么想法吗?
如何
【问题讨论】: