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

为何无法使用Text="{Binding City, Source={Binding Address}}"这类绑定语法?

为什么这两种XAML绑定写法无法正常工作?

先看原有的可正常运行代码:

模型类代码

public class Person
{
    public Address Address { get; set; } = null!;
}
public class Address
{
    public string City { get; set; } = null!;
}

页面后台代码

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        BindingContext = new Person
        {
            Address = new Address { City = "New York" }
        };
    }
}

可正常运行的XAML标签

<Label Text="{Binding}" BindingContext="{Binding Address.City}" />

以上代码能正常显示"New York",但为什么改成下面两种写法就不行?

无法正常工作的两种写法

<Label Text="{Binding City, Source={Binding Address}}" />
<Label Text="{Binding}" BindingContext="{Binding City, Source={Binding Address}}" />

原因解析

问题出在**Source={Binding Address}这种嵌套绑定的写法不符合XAML绑定语法**:

  • 在XAML绑定规则里,Source属性的作用是指定绑定的数据源对象,它需要接收具体的对象实例(比如ViewModel实例、某个UI元素),或者RelativeSource/ElementName这类特殊标记,不能直接用{Binding ...}这种绑定表达式来赋值。{Binding ...}本身是创建一个Binding实例,无法作为另一个Binding的Source参数。
  • 第一种写法里,你试图用{Binding Address}作为Source来绑定City,XAML解析器无法解析这种嵌套的绑定逻辑,自然无法正常工作。
  • 第二种写法同理,BindingContext可以直接绑定到{Binding Address.City},但你用Source={Binding Address}的方式指定源再绑定City,本质还是犯了嵌套绑定的语法错误。

正确的替代写法

如果想拆分绑定逻辑,合理的写法应该是这样:

<Label BindingContext="{Binding Address}" Text="{Binding City}" />

或者最简洁的直接路径绑定:

<Label Text="{Binding Address.City}" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:32:23