繁体   English   中英

使用 DataTemplate 在 ItemsControl 中传递对象

[英]Passing objects in ItemsControl using a DataTemplate

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

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 ,每当我点击一个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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM