【问题标题】:Access ViewModel property from ViewCell从 ViewCell 访问 ViewModel 属性
【发布时间】:2026-01-12 00:50:02
【问题描述】:

我有一个 ViewModel 类,它有一个名为 Title 的 String 类型的属性。

在我的视图中,我有一个 Comment 类型的 ListView。我想在我的 ViewCell 中访问我的 ViewModel 的 Title 属性。因为 ViewCell 有不同的 BindingContext 我不能这样做:'{Binding Title}'

有人知道我如何访问 ViewCell 中的 ViewModel 属性吗?

【问题讨论】:

  • 您是否尝试过使用源和路径进行绑定,例如这里? forums.xamarin.com/discussion/comment/144204/#Comment_144204
  • 你想对标题做什么?您是否尝试在 ViewCell 的 XAML 中绑定到它,或者您是否尝试在点击项目时访问它等? @Jauhenka 的建议链接显示了如何绑定到另一个元素(绑定源路径),因此您可以绑定到 ListView 的 DataContext 以访问标题。

标签: xamarin xamarin.ios xamarin.android xamarin.forms


【解决方案1】:

我可能是这样的:

<Label Text="{Binding Source={x:Reference this}, Path=BindingContext.Title}"></Label>

其中,x:Reference 是页面本身,它的声明如下:

<ContentPage x:Name="this" ... >

【讨论】: