通过绑定访问当前ItemsControl索引
本文关键字:ItemsControl 索引 访问 绑定 | 更新日期: 2023-09-27 18:17:50
我有以下一段代码
<ItemsControl x:Name="ItemsControl" ItemsSource="{Binding Offers}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<wpf:Card Padding="32" Margin="5" d:DataContext="{d:DesignData }">
<StackPanel Margin="0,0,0,-30" Height="107">
<TextBlock
Style="{DynamicResource MaterialDesignTitleTextBlock}">
<Run Text="Offer " />
</TextBlock>
<TextBlock Text="{Binding CarDescription}" />
<Separator Height="1" Visibility="Hidden" />
<Button Content="Select"
Width="72"
VerticalAlignment="Bottom"
HorizontalAlignment="Right"
Margin="0,20,0,0"
Command="{Binding SelectOfferCommand}"/>
</StackPanel>
</wpf:Card>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
这会产生一堆重复的盒子,每个盒子都有一个按钮。每次我点击按钮,我想访问当前框索引(从ItemsControl的ItemsSource),并将其作为命令参数传递。有可能做到吗?
可以通过AlterationIndex
传递当前ItemsControl
的Index
在这里查看更多信息
的例子:
<ItemsControl x:Name="ItemsControl"
ItemsSource="{Binding Offers}"
AlternationCount="1000">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<wpf:Card Padding="32" Margin="5" d:DataContext="{d:DesignData }">
<StackPanel Margin="0,0,0,-30" Height="107">
<TextBlock
Style="{DynamicResource MaterialDesignTitleTextBlock}">
<Run Text="Offer " />
</TextBlock>
<TextBlock Text="{Binding CarDescription}" />
<Separator Height="1" Visibility="Hidden" />
<Button Content="Select"
Width="72"
VerticalAlignment="Bottom"
HorizontalAlignment="Right"
Margin="0,20,0,0"
Command="{Binding SelectOfferCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentPresenter}}, Path=(ItemsControl.AlternationIndex)}"/>
</StackPanel>
</wpf:Card>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
可能适合您在创建Offers
时将index
属性添加到每个Offer
并发送此索引OnSelectOfferCommand。这样就容易多了
ps我想我必须解释我的答案:我的建议不仅更容易实现,而且将业务逻辑与UI分开也是一个很好的实践。在这种情况下,如果UI将被更改,更改将不会影响整个订购过程