使用 DataTemplate 在 ItemsControl 中传递对象

Passing objects in ItemsControl using a DataTemplate

所以基本上我有一个 class 步骤。

public class Step : INotifyPropertyChanged
{
    public int Index { get; set; }
    public int Time { get; set; }
}

在我的 xaml 中,我想使用一个 DataTemplate 和一个 ItemsControl 来表示步骤。我的数据模板如下所示:

<DataTemplate x:Key="StepTemplate" DataType="data:Step">
    <Label Content="{Binding Index}"/>
    <Label Content="{Binding Time}"/>
</DataTemplate>

我的 ItemsControl 看起来像这样。

<ItemsControl Name="ListSteps" ItemsSource="{Binding Steps}" Grid.IsSharedSizeScope="True" ItemTemplate="{StaticResource StepTemplate}" >
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding Path=DataContext.StepClick, ElementName=ListSteps}" CommandParameter="{Binding}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ItemsControl>

几乎应该发生的事情: 每当我单击 Step 时,都会调用方法 StepClick 并调用我单击的 Step 对象作为参数传递。

实际发生了什么: 每当我单击 Step 时,都会调用方法 StepClick,但不会将步骤对象作为参数,但传递了我视图的一个对象。这根本不是我想要的。

如何在我点击 Step 时传递 Step 的对象?

将交互触发器移动到 ItemTemplate 的根元素:

<DataTemplate x:Key="StepTemplate" DataType="data:Step">
    <StackPanel Background="Transparent">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseLeftButtonDown">
                <i:InvokeCommandAction Command="{Binding Path=DataContext.StepClick, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
                                       CommandParameter="{Binding}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        <Label Content="{Binding Index}"/>
        <Label Content="{Binding Time}"/>
    </StackPanel>
</DataTemplate>