所以,我正在设计一个通用Windows应用程序,该应用程序使用ListView绑定到它的数据,我以编程方式创建。我页面的XAML:
<ListView x:Name="lvEpisodeListSource" Margin="10,170,10,10" ItemsSource="{Binding Source={StaticResource EpisodeListSource}}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Episode">
<ListViewItem Background="CadetBlue" IsDoubleTapEnabled="False" IsHoldingEnabled="False" Tapped="ListViewItem_Tapped" IsRightTapEnabled="False" HorizontalAlignment="Stretch">
<TextBlock Name="AlbumBlock" Foreground="Black" FontWeight="Normal" FontSize="15" Margin="5,0,0,0"
Text="{x:Bind Name}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</ListViewItem>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
数据绑定正确,一切正常。我试图将最近点击的ListViewItem保存到LocalApplicationData。目前,我正在尝试通过在项目的tapped事件中设置本地应用程序数据来实现此目的。
private void ListViewItem_Tapped(object sender, TappedRoutedEventArgs e)
{
myData data = ((ListViewItem)sender).DataContext as myData;
var clickedNumber = lvDataListSource.Items.IndexOf(((ListViewItem)sender));
}
目前无效,clickedNumber
总是返回-1,无论我点击哪一个。有没有办法获得调用tapped事件的项目的索引,还是有更好的方法来实现我想要完成的事情?
谢谢!
答案 0 :(得分:0)
获取与整个ListView
相对应的索引或数据(父上下文)而不是ListViewItem
(子上下文)总是更好。
将您的XAML更改为以下。
<ListView x:Name="lvEpisodeListSource" Margin="10,170,10,10" ItemsSource="{Binding Source={StaticResource EpisodeListSource}}" SelectionChanged="ListView_SelectionChanged>
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Episode">
<TextBlock Name="AlbumBlock" Foreground="Black" FontWeight="Normal" FontSize="15" Margin="5,0,0,0"
Text="{x:Bind Name}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
您的选择更改事件将是
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListView view = (ListView)sender;
//Get Index of Selected Item
var index = view.SelectedIndex;
//Get Selected Item
var selectedItem = view.SelectedItem;
}
我建议总是引用父资源并尝试向下钻取到子项,除非您有一个子项单击事件,它提供了直接资源来获取父项。