You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

跟随Xamarin基础教程遇XamlParseException:无法找到Assignments引用

Xamarin.Forms绑定RemoveAssignmentCommand触发XamlParseException的解决办法

问题描述

实现跨移动平台待办列表功能时,XAML中ImageButton绑定RemoveAssignmentCommand时触发Xamarin.Forms.Xaml.XamlParseException,错误提示:

Position 30:37. Can not find the object referenced by Assignments

移除该绑定后程序可正常运行。

错误原因

问题出在ImageButton的Command绑定代码:

Command="{Binding Path=BindingContext.RemoveAssignmentCommand, Source={x:Reference Assignments}}"

x:Reference用于引用XAML页面中带有x:Name属性的UI元素,但Assignments是AssignmentViewModel中的集合属性,并非页面上的命名UI元素,因此XAML解析器无法找到对应的引用对象,抛出异常。

修复方案

有两种可行的修复方式:

方式一:通过ListView的命名引用获取ViewModel命令

ListView的x:Name为AssignmentList,它的BindingContext与页面一致(即AssignmentViewModel),因此可以通过引用ListView来获取ViewModel中的命令:

<ImageButton 
    Source="delete.png" 
    Scale="0.5"
    Command="{Binding Path=BindingContext.RemoveAssignmentCommand, Source={x:Reference AssignmentList}}"
    CommandParameter="{Binding .}"
/>

方式二:使用RelativeSource向上查找页面的BindingContext

不依赖UI元素命名,通过RelativeSource向上查找ContentPage类型的祖先,直接获取页面的BindingContext:

<ImageButton 
    Source="delete.png" 
    Scale="0.5"
    Command="{Binding Path=BindingContext.RemoveAssignmentCommand, RelativeSource={RelativeSource AncestorType={x:Type ContentPage}}}"
    CommandParameter="{Binding .}"
/>

验证

修改后,点击ImageButton即可正确触发RemoveAssignmentCommand,将对应的待办项从Assignments集合中移除,程序运行正常。

内容的提问来源于stack exchange,提问作者churuzzz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:40:26