MAUI Community Toolkit长按手势参数错位问题求助
MAUI Community Toolkit长按手势反向插入数据时错位问题解决
问题分析
通过Insert(0, NewItem)反向向ObservableCollection添加数据到CollectionView后,左右滑动功能能正确返回对应项,但长按手势的CommandParameter出现错位;正常插入数据时功能完全正常。这是CollectionView的视图复用机制导致的:子元素上的TouchBehavior绑定未在视图复用时正确更新,旧的项参数被保留,最终引发错位。
解决方案
将TouchBehavior从Grid的Behaviors移动到SwipeView(ItemTemplate的根元素)的Behaviors中,确保视图复用时,TouchBehavior能直接感知当前项的BindingContext变化,正确更新CommandParameter。
修改后的完整代码
<CollectionView Margin="10" x:Name="RigheCocoCollection" ItemsSource="{Binding ArticoliCollection}" SelectionMode="Single" SelectedItem="{Binding ArticoloPerModifica}" BackgroundColor="DarkCyan" HeightRequest="320"> <CollectionView.Header> <VerticalStackLayout> <Label HeightRequest="25" VerticalTextAlignment="Center" HorizontalOptions="Center" Text="Righe Copia Commissione" FontAttributes="Bold" FontSize="15" TextColor="White"/> </VerticalStackLayout> </CollectionView.Header> <CollectionView.ItemTemplate> <DataTemplate x:DataType="ModelCoco:RigaCoco"> <SwipeView> <!-- 将TouchBehavior移到SwipeView的Behaviors中 --> <SwipeView.Behaviors> <Toolkit:TouchBehavior LongPressCommand="{Binding BindingContext.DeleteRowCommand, Source={x:Reference this}}" LongPressCommandParameter="{Binding .}" LongPressDuration="1000"/> </SwipeView.Behaviors> <SwipeView.RightItems> <SwipeItem Text="Test" BackgroundColor="Red" CommandParameter="{Binding .}" Command="{Binding BindingContext.TestCommand, Source={x:Reference this}}"/> </SwipeView.RightItems> <SwipeView.LeftItems> <SwipeItem Text="Test 2" BackgroundColor="Red"/> </SwipeView.LeftItems> <Border BackgroundColor="AntiqueWhite" Padding="5" StrokeThickness="2" Stroke="Black"> <Grid ColumnDefinitions="Auto,*,*" RowDefinitions="20,32,20" ColumnSpacing="5"> <Label Text="{Binding cod_articolo}" Grid.ColumnSpan="3"/> <Label Grid.Row="1" Text="{Binding descr_1}" Grid.ColumnSpan="3" FontSize="13"/> <Label Grid.Row="2" Text="{Binding Unita_misura}"/> <Label Grid.Row="2" Grid.Column="1" Text="{Binding quantita}"/> <Label Grid.Row="2" Grid.Column="2" Text="{Binding Prezzo, StringFormat='€ {0:F4}'}"/> </Grid> </Border> </SwipeView> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView>
额外验证优化
- 确保
ArticoliCollection是ObservableCollection<RigaCoco>,保证集合变化时UI能正确响应。 - 若问题仍存在,可给
LongPressCommandParameter绑定显式添加Mode=OneWay,强制绑定随BindingContext更新:LongPressCommandParameter="{Binding ., Mode=OneWay}"
内容的提问来源于stack exchange,提问作者Stefano Santin
相关产品推荐
相关产品推荐

