在DataTemplate中绑定自定义控件



我已经解决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使用的绑定上下文似乎是PhotoViewBindingContext,而不是DataTemplate的上下文,因为Label在下面几行。

如果这是WPF,我会把绑定改为

Persona="{Binding DataContext,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListBoxItem}}"

这可能已经修复了它,但在这里不起作用(RelativeSource显然没有定义)。

为什么?如何使Persona绑定到DataTemplate的上下文,就像Label的情况一样?

Xamarin.Forms(最高1.2.x)绑定始终使用BindableObject.BindingContext作为上下文绑定。

在模板项的情况下,项上下文设置为模板元素,在本例中为ViewCell,并递归设置为ViewCell.ViewStackLayout您的PhotoView、内部StackLayout和2个Labels。

CCD_ 18和CCD_。

所以,当你说

[...] for the custom control PhotoView it seems that the binding context used by 
{Binding} to the property Persona is the PhotoView's BindingContext, not the 
DataTemplate's context, [...]

这是对的,也是错的。

{Binding}使用的绑定上下文是PhotoView的Bindingcontext,也是DataTemplate的上下文

如果Binding没有像您预期的那样工作,可能是因为PhotoView以某种方式将BindingContext设置为this,并阻止{Binding}按预期工作,但我不能说没有看到PhotoView的代码。

最新更新