You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ListView的ItemTapped与ItemSelected事件不触发问题及数据访问咨询

问题分析与解决方案

嘿,我一眼就揪出问题所在了——你的事件绑定位置错啦!这就是ItemTapped和ItemSelected始终没触发的核心原因。

一、事件绑定位置错误的问题

你把ItemTapped和ItemSelected属性写在了<ListView.ItemTemplate>标签上,但这两个事件是ListView控件本身的事件,根本不属于ItemTemplate。正确的做法是把它们移到<ListView>主标签里。

修正后的XAML代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             x:Class="BudgetBuddy.SQL">
    <ContentPage.Content>
        <!-- 把事件绑定移到ListView主标签上 -->
        <ListView x:Name="ListView" 
                  ItemTapped="MyItemTapped" 
                  ItemSelected="MyItemSelected">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Name}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>
</ContentPage>

二、获取点击项的Value值

接下来解决第二个问题:要拿到点击项对应的Value,你需要修改事件方法的参数类型——原来的System.EventArgs太宽泛了,得用对应事件的专属参数类才能拿到选中的对象:

修正后的C#事件方法:

void MyItemTapped(object sender, ItemTappedEventArgs e)
{
    // 先判断点击的项是否为Settings类型
    if (e.Item is Settings tappedSetting)
    {
        // 直接读取对应的Value属性
        DisplayAlert("Alert", $"You pressed: {tappedSetting.Value}", "OK");
    }
    // 可选操作:清除选中状态,避免重复触发ItemSelected事件
    ((ListView)sender).SelectedItem = null;
}

void MyItemSelected(object sender, SelectedItemChangedEventArgs e)
{
    if (e.SelectedItem is Settings selectedSetting)
    {
        DisplayAlert("Alert", $"You selected: {selectedSetting.Value}", "OK");
    }
}

额外小提示

另外,你在OnAppearing里每次页面显示都插入一条数据,这样每次打开页面都会新增重复的"Meaning of Life"记录,建议加个判断逻辑,避免重复插入:

var existingItem = await _connection.Table<Settings>().FirstOrDefaultAsync(s => s.Name == "Meaning of Life");
if (existingItem == null)
{
    await _connection.InsertAsync(settings_name);
    await DisplayAlert("Alert", "Value Added to database!", "OK");
}

内容的提问来源于stack exchange,提问作者John Cadac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:35:48