Xamarin中DataTemplate内Label的TextColor如何绑定页面BindingContext
问题原因
CollectionView 的 DataTemplate 内部默认绑定上下文是 ItemsSource 对应集合中的单个元素对象,你直接写 {Binding TextColor} 会优先查找单个列表项对象的属性,自然无法匹配到页面级绑定上下文的属性。
解决方法
有两种常用的实现方案:
方案1:通过元素引用绑定
首先给你的页面根节点(通常是 ContentPage)添加 x:Name 属性,示例:
<ContentPage ... x:Name="CurrentPage">
然后修改 Label 的 TextColor 绑定,指定绑定源为你命名的页面即可:
<Label Text="{Binding AttributFromListObject}" TextColor="{Binding BindingContext.TextColor, Source={x:Reference CurrentPage}}" Grid.Row="0" Grid.Column="0"/>
路径里加 BindingContext 是因为我们拿到的 CurrentPage 是页面元素本身,它的 BindingContext 属性才是你在后台设置的页面级视图模型,需要先指向它才能访问到对应的 TextColor 属性。
方案2:通过相对绑定查找父级上下文(更灵活,无需手动命名)
直接通过 RelativeSource 沿着视觉树向上查找页面级父元素,自动获取绑定上下文,不需要给页面加额外名称:
<Label Text="{Binding AttributFromListObject}" TextColor="{Binding BindingContext.TextColor, RelativeSource={RelativeSource AncestorType={x:Type ContentPage}}}" Grid.Row="0" Grid.Column="0"/>
如果需要绑定的属性在 CollectionView 对应的上层上下文里,也可以把 AncestorType 替换为 CollectionView,效果一致。
内容的提问来源于stack exchange,提问作者guiwhatsthat
相关产品推荐
相关产品推荐

