Reputation: 4777
I have the following ItemsControl which handles the display of items added to it:
<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>
You can see that the Button has a Command="{Binding}" which handles the click event and calls a command.
Now I want to also use a ListView to display the same items and handle the click event. I see from this link WPF: How to bind a command to the ListBoxItem using MVVM? that I have to use Interaction.Triggers so I have did the following:
<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>
The items display properly in the ListView so I know the binding is correct for the text display but I find that the click handler for the ListView does not fire the command like the Button object does.
Any ideas?
How
Upvotes: 2
Views: 2790
Reputation: 169390
You should apply the interaction trigger to an element within the ListView
. You could use a CellTemplate
with a TextBlock
that you apply the interaction trigger to:
<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">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DisplayValue}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction Command="{Binding}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</ControlTemplate>
Upvotes: 2