ListView的ItemSelected事件在列表项为ContentView包裹的SwipeView时不触发
问题根因
你遇到的是Xamarin.Forms 5.0.0.2012 Android端的已知触摸事件传递问题:当SwipeView被外层ContentView包裹时,SwipeView消费了触摸事件后不会向上冒泡给父级ViewCell,因此ListView无法识别选中操作,而滑动操作是SwipeView自身处理的,所以不受影响。
可行解决方案
方案1:调整控件嵌套结构(推荐,无额外编码)
把ContentView挪到SwipeView内部作为其内容承载,既保留你动态切换内容的需求,又能正常触发ItemSelected事件。
修改后示例代码:
<?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="App2.MainPage"> <StackLayout> <ListView x:Name="EmployeeView" ItemSelected="EmployeeView_ItemSelected"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <SwipeView> <SwipeView.LeftItems> <SwipeItems> <SwipeItem Text="Favorite" BackgroundColor="Blue"/> <SwipeItem Text="Delete" BackgroundColor="LightPink" /> </SwipeItems> </SwipeView.LeftItems> <!-- ContentView移到SwipeView内部作为内容容器 --> <ContentView x:Name="DynamicContent"> <!-- 可通过触发器动态切换此处内容,不需要滑动时直接替换为只读Grid --> <StackLayout Orientation="Horizontal" BackgroundColor="GreenYellow"> <Label Text="{Binding Name}"/> <Label Text="{Binding Age}"/> </StackLayout> </ContentView> </SwipeView> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackLayout> </ContentPage>
不需要滑动的列表项,你可以直接通过触发器把SwipeView的滑动项置空,或者直接替换DynamicContent的内容即可,不会额外实例化冗余控件,完全可以解决你提到的列表加载卡顿问题。
方案2:添加点击手势手动触发选中
如果你必须保留ContentView包裹SwipeView的结构,可以给SwipeView的内容容器加点击手势,手动触发选中逻辑:
- 后台添加点击事件处理:
private void OnContentTapped(object sender, TappedEventArgs e) { var selectedItem = e.Parameter as 你的数据模型类; // 手动赋值SelectedItem触发ItemSelected事件 EmployeeView.SelectedItem = selectedItem; }
- XAML中给内容容器添加手势:
<StackLayout Orientation="Horizontal" BackgroundColor="GreenYellow"> <StackLayout.GestureRecognizers> <TapGestureRecognizer Tapped="OnContentTapped" CommandParameter="{Binding .}"/> </StackLayout.GestureRecognizers> <Label Text="{Binding Name}"/> <Label Text="{Binding Age}"/> </StackLayout>
内容的提问来源于stack exchange,提问作者DhaKau
相关产品推荐
相关产品推荐

