.NET MAUI中TouchBehavior绑定CommandParameter刷新数据后传值异常
问题原因分析
CollectionView为了提升性能会复用DataTemplate中的UI元素(比如你用的Button)。当列表数据刷新时,旧的Button会被重新绑定到新的数据项:
- Button自身的
CommandParameter绑定会随着Button的BindingContext更新自动刷新,因为控件的绑定上下文变更机制会同步更新自身的绑定。 - 但
TouchBehavior作为附加到Button上的行为,它的CommandParameter="{Binding .}"是绑定自身的BindingContext,而Behavior的BindingContext不会自动跟随宿主Button的BindingContext变化——元素复用时,Behavior的旧绑定上下文没有被替换为新的数据项,导致传递的参数还是刷新前的旧项。
解决方案
方案1:直接绑定到Button的BindingContext
修改TouchBehavior的参数绑定源,明确关联到Button的BindingContext,这样就能跟随Button的绑定上下文(也就是CollectionView的当前项)同步更新:
<Button Text="GoTo"> <Button.Behaviors> <toolkit:TouchBehavior Command="{Binding Source={x:Reference MyView}, Path=BindingContext.ItemClickedCommand}" CommandParameter="{Binding Source={RelativeSource AncestorType={x:Type Button}}, Path=BindingContext}" LongPressCommand="{Binding Source={x:Reference MyView}, Path=BindingContext.ItemLongClickedCommand}" LongPressCommandParameter="{Binding Source={RelativeSource AncestorType={x:Type Button}}, Path=BindingContext}" LongPressDuration="250" /> </Button.Behaviors> </Button>
方案2:让Behavior继承Button的BindingContext
给TouchBehavior设置BindingContext为Button的上下文,这样原来的{Binding .}就能正确指向当前数据项:
<Button Text="GoTo"> <Button.Behaviors> <toolkit:TouchBehavior BindingContext="{Binding Source={RelativeSource AncestorType={x:Type Button}}}" Command="{Binding Source={x:Reference MyView}, Path=BindingContext.ItemClickedCommand}" CommandParameter="{Binding .}" LongPressCommand="{Binding Source={x:Reference MyView}, Path=BindingContext.ItemLongClickedCommand}" LongPressCommandParameter="{Binding .}" LongPressDuration="250" /> </Button.Behaviors> </Button>
额外注意事项
确保你的列表数据是通过ObservableCollection管理的,并且刷新数据时:
- 如果是替换集合中的项,直接修改集合内容即可(ObservableCollection会自动通知UI更新);
- 如果是重新赋值集合引用,要确保集合属性触发了
INotifyPropertyChanged.PropertyChanged事件。
内容的提问来源于stack exchange,提问作者Pl Oe
相关产品推荐
相关产品推荐

