需求:ListBox中的Item是按鈕圖檔,要求單擊和輕按兩下時觸發不同的事件。
XAML中需要引入System.Windows.Interactivity.dll
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
該ListBox的關鍵代碼如下。
<ListBox ItemsSource="{Binding YourList}">
<ListBox.Template>
<!-- 流式布局 左對齊 -->
<ControlTemplate TargetType="ListBox">
<WrapPanel Width="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext.YourWidth}" Orientation="Horizontal" IsItemsHost="True"/>
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<!-- 單擊事件,傳參Button自身 -->
<Button Width="160" Height="120" Background="Transparent" BorderBrush="#E12080" BorderThickness="1"
Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext.YourClickCommand}"
CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}" BorderBrush="#E12080" BorderThickness="1">
<!-- 輕按兩下事件,傳參父節點的Button -->
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction
Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext.YourDoubleClickCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type Button}}}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid>
<!-- ListBoxItem的内容 -->
</Grid>
</Button>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>