如何在使用了DataTemplate的ListBox中,根据DataTemplate中的控件获取ListBoxItem
问题描述:
我有一个ListBox,使用ListBox.ItemTemplate和DataTempltae定义了每一个ListBoxItem,在DataTemplate中,有其他控件。
假设DataTemplate中有一个Button和一个TextBlock,我现在想点击Button,然后想得到该Button所处的ListBoxItem
代码:
- XML code
<ListBox ItemsSource="{Binding Data}"> <ListBox.ItemTemplate> <DataTemplate x:Name="Item"> <StackPanel> <TextBlock Text="{Binding time}"/> <Button Content="Click" Name="Btn" Click="Btn_Click"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate></ListBox>
具体问题:
现在,ListBox有很多个ListBoxItem,而每一个ListBoxItem都有一个Btn,请问如何实现在点击Btn的时候,获取到对应的ListBoxItem呢?
[解决办法]
button 的 tap 属性绑定到 Data 的下标,比如Index
- XML code
<ListBox ItemsSource="{Binding Data}"> <ListBox.ItemTemplate> <DataTemplate x:Name="Item"> <StackPanel> <TextBlock Text="{Binding time}"/> <Button Content="Click" Name="Btn" Click="Btn_Click" Tap="{Binding Index}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate></ListBox>