【发布时间】:2014-10-07 16:06:46
【问题描述】:
一段时间以来,我一直在解决有关 XAML 中数据绑定的问题。
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Pedagouge.Views;assembly=Pedagouge"
x:Class="Pedagouge.Views.StudentGroupView">
<StackLayout>
<ListView x:Name="Students">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<local:PhotoView x:Name="Photo" Persona="{Binding}" />
<StackLayout Orientation="Vertical" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand">
<Label Text="{Binding FullName}" />
<Label Text="{Binding StudentIsAt.Group.Name}" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
我以为我已经想到了绑定,但我遇到的问题清楚地表明我没有。
无论如何,问题在于对于自定义控件PhotoView,似乎{Binding} 使用的属性Persona 的绑定上下文是PhotoView 的BindingContext,而不是DataTemplate 的上下文,就像Labels 向下几行一样。
如果这是 WPF,我会直接将绑定更改为
Persona="{Binding DataContext,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListBoxItem}}"
这可能会修复它,但在这里不起作用(RelativeSource 显然没有定义)。
怎么会?我怎样才能让Persona 绑定到DataTemplates 上下文,就像Labels 的情况一样?
【问题讨论】:
-
如果在视图模型上添加属性
Self { get { return this; } },然后将 PhotoView.Persona 上的绑定更改为{Binding Self},会怎样?另外..看看这个:stackoverflow.com/questions/22595388/… -
@mrtig 听起来这仍然会给我一个对视图模型的引用,而不是当前绑定到 DataTemplate 的项目
-
是的,我想你是对的。您可以尝试绑定集合的每个成员的“self”属性。 ..或者您可以尝试
ElementName建议(在上面的链接中)。 -
ElementName解决方案只生成NullPointerException。我确实首先将整个 ViewCell 移到了它自己的控件中。
标签: xamarin.forms