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

MAUI中绑定父级ViewModel为命令源时XAML语法报错如何解决

MAUI父级ViewModel绑定报错问题解答

错误原因

你遇到的缺少'}'类报错均为XAML绑定表达式语法错误导致,两种写法都存在同一个共性问题:Binding表达式的路径参数和后续的RelativeSource/Source参数之间没有添加逗号分隔,再加上换行书写时的格式问题,导致XAML解析器无法正常识别绑定结构,触发语法报错。

除此之外还有一个隐含逻辑问题:你通过RelativeSource或者x:Reference取到的父级对象是ParentPage页面类实例本身,如果你要绑定的SelectTab命令是定义在页面绑定的ParentViewModel中,需要在路径前加上BindingContext前缀,否则会绑定到页面类本身不存在的属性,触发运行时绑定失败。

修正后的正确写法

1. RelativeSource 写法

<ContentPage ... x:Class="ParentPage" x:DataType="ParentViewModel" x:Name="Parent">
    <StackLayout>
        <ListView ItemsSource="{Binding Tabs}">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="TabViewModel">
                    <ViewCell>
                        <Button Text="Do it"
                                Command="{Binding BindingContext.SelectTab, 
                                          RelativeSource={RelativeSource AncestorType={x:Type ParentPage}}}" />
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

2. x:Reference 写法

<ContentPage ... x:Class="ParentPage" x:DataType="ParentViewModel" x:Name="Parent">
    <StackLayout>
        <ListView ItemsSource="{Binding Tabs}">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="TabViewModel">
                    <ViewCell>
                        <Button Text="Do it"
                                Command="{Binding BindingContext.SelectTab, 
                                          Source={x:Reference Parent}}" />
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

参考说明

MAUI绑定相关的完整语法、用法规范可在微软官方MAUI文档的「数据绑定」模块下查阅,覆盖编译绑定、相对绑定、模板绑定等所有场景的使用说明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:06:02