如何检查单击了ListView中ListItem的哪个字符串资源?

How to check which string resource of a ListItem in a ListView was clicked?

有没有办法检查 ListView item click 的字符串资源而不是 ListView 的索引(这在教程中经常演示)? 例如我有一个包含 3 个项目的 ListView:"Item A"、"Item B" 和 "Item C"。如果点击的ListView项的字符串资源是"Item A",做点什么。

主页class

public sealed partial class MainPage : Page
{
    private List<ListItemMain> mainItems;

    public MainPage()
    {
        this.InitializeComponent();

        gridItemMains = MainItemManger.GetGridItems();
    }

    private void ListView_ItemClick(object sender, ItemClickEventArgs e)
    {

    }
}

项目class

public class ListItem
    {
        public string Name { get; set; }
    }

    public class BookManger
    {
        public static List<Book> GetListItems()
        {
            var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();

            var items = new List<Book>
            {
                new Book { Name = resourceLoader.GetString("ItemA") },
                new Book { Name = resourceLoader.GetString("ItemB") },
                new Book { Name = resourceLoader.GetString("ItemC") }
            };

            return items;
        }
    }

XAML

<Page
    x:Class="My_App.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:data="using:My_App.Models"
    mc:Ignorable="d">

        <ListView ItemsSource="{x:Bind listItems}" ItemClick="ListView_ItemClick">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="data:ListItem">
                    <StackPanel>
                        <TextBlock Text="{Binding Book}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</Page>

您需要将 IsItemClickEnabled 属性 设置为 true 才能从 ListView.

获取 ItemClick 事件

请参阅 ItemClick Event 的文档页面。

更新后的 XAML 如下所示:

<ListView ItemsSource="{x:Bind listItems}" ItemClick="ListView_ItemClick" IsItemClickEnabled="True">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="data:ListItem">
            <StackPanel>
                <TextBlock Text="{Binding Book}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

以及事件处理程序代码:

void ListView_ItemClick(object sender, ItemClickEventArgs e)
{
    // TODO: Add your code by accessing e.ClickedItem here
}