.NET MAUI中DataTemplate绑定旧引用问题排查与解决
解决方案
方法1:强制刷新绑定(推荐)
核心是在模板控件的绑定上下文变更时,手动更新命令参数,确保关联当前数据项:
// TestCard.xaml.cs protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); if (BindingContext is TestItem currentItem) { // 假设TouchBehavior的x:Name为TouchBehavior TouchBehavior.CommandParameter = currentItem; } }
同时在XAML中明确绑定命令参数到当前DataContext,避免残留旧引用:
<toolkit:TouchBehavior LongPressCommand="{Binding ShowTestContextPopupCommand}" LongPressCommandParameter="{Binding}" />
方法2:禁用模板回收
如果不介意性能损耗,可关闭CollectionView的模板回收机制,让每个新项都使用全新模板:
<CollectionView ItemsSource="{Binding BrowsingItems}" DataTemplateSelector="{StaticResource YourTemplateSelector}" IsItemTemplateRecyclingEnabled="False" />
注意:该方法会增加内存占用,列表项较多时不建议使用。
方法3:动态获取当前数据项
修改命令逻辑,直接从触发控件的绑定上下文获取最新数据,不依赖缓存的参数:
// MainViewModel.cs public ICommand ShowTestContextPopupCommand => new Command<object>(parameter => { if (parameter is VisualElement element && element.BindingContext is TestItem currentItem) { // 这里使用currentItem处理弹窗逻辑 ShowPopup(currentItem.Name); } });
对应XAML将命令参数绑定到控件自身:
<toolkit:TouchBehavior LongPressCommand="{Binding ShowTestContextPopupCommand}" LongPressCommandParameter="{Binding RelativeSource={RelativeSource Self}}" />
方法4:确保数据模型实现INotifyPropertyChanged
确认TestItem实现INotifyPropertyChanged接口,保证绑定能及时响应数据变更:
public class TestItem : IBaseItem, INotifyPropertyChanged { private string _name; public string Name { get => _name; set { _name = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
内容的提问来源于stack exchange,提问作者Jan Jonáš
相关产品推荐
相关产品推荐

