代码之家  ›  专栏  ›  技术社区  ›  user2877820

使用DataTemplate在ItemsControl中传递对象

  •  1
  • user2877820  · 技术社区  · 7 年前

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

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

    在我的xaml中,我想使用一个数据模板和一个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 调用,并将我单击的步骤对象作为参数传递。

    实际发生的情况: 每当我点击 单步单击 调用,但不是作为参数传递步骤对象,而是传递视图的对象。这根本不是我想要的。

    我如何传递物体 每当我点击 ?

    1 回复  |  直到 7 年前
        1
  •  1
  •   mm8    7 年前

    将交互触发器移动到 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>