【问题标题】:Passing objects in ItemsControl using a DataTemplate使用 DataTemplate 在 ItemsControl 中传递对象
【发布时间】:2017-10-23 12:31:37
【问题描述】:

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

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 Object 作为参数传递,而是传递我的视图对象.这根本不是我想要的。

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

【问题讨论】:

    标签: c# wpf datatemplate


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      相关资源
      最近更新 更多