.NET MAUI中CollectionView点击Frame内部时SelectionChanged不触发
.NET MAUI CollectionView点击Frame内容不触发SelectionChanged问题
在.NET MAUI中创建CollectionView并在数据模板内使用Frame控件后,点击Frame内部内容时SelectionChanged方法不会触发,仅点击Frame边框或外部区域时才会触发。相同设置在Xamarin中可正常运行。
示例代码
<CollectionView x:Name="scheduleItemsCollection" SelectionChanged="scheduleItemsCollection_SelectionChanged" SelectionMode="Single" > <CollectionView.ItemsLayout> <GridItemsLayout Orientation="Vertical" Span="2" /> </CollectionView.ItemsLayout> <CollectionView.ItemTemplate> <DataTemplate> <Grid Padding="5" RowSpacing="0"> <Frame CornerRadius="40" BorderColor="Gray"> <StackLayout Spacing="0" BackgroundColor="White"> <Label Text="{Binding bookingDayArabic}" /> <Label Text="{Binding bookingDateD}" /> <StackLayout Orientation="Horizontal"> <Label Text="{Binding slotsAvailable}" HorizontalOptions="CenterAndExpand" /> <Label Text="عدد الطلبات:"/> </StackLayout> </StackLayout> </Frame> </Grid> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView>
效果截图

问题原因与解决方法
这不是MAUI的BUG,是MAUI中Frame控件的默认行为变化导致的:Xamarin里Frame不会拦截点击事件,而MAUI中Frame会捕获点击,导致CollectionView的项选择事件无法触发。
解决方法1:让Frame不拦截点击
给Frame设置InputTransparent="True",让点击事件穿透到CollectionView的项容器:
<Frame CornerRadius="40" BorderColor="Gray" InputTransparent="True"> <!-- 内部内容不变 --> </Frame>
解决方法2:保留Frame交互并手动触发选择
如果需要Frame保留自身的交互效果(比如点击反馈),可以给Frame添加点击手势,手动设置CollectionView的选中项:
XAML修改:
<Frame CornerRadius="40" BorderColor="Gray"> <Frame.GestureRecognizers> <TapGestureRecognizer Tapped="Frame_Tapped" CommandParameter="{Binding}" /> </Frame.GestureRecognizers> <!-- 内部内容不变 --> </Frame>
后台代码:
private void Frame_Tapped(object sender, EventArgs e) { var tappedItem = ((TapGestureRecognizer)sender).CommandParameter; scheduleItemsCollection.SelectedItem = tappedItem; }
内容的提问来源于stack exchange,提问作者Ali Alfaraj
相关产品推荐
相关产品推荐

