2014-10-04 119 views
1

我一直在解决有关XAML中的数据绑定问题。绑定DataTemplate中的自定义控件

<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 SA几排下来。

,如果获得WPF,我会只是改变了结合

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

而且很可能有固定的,但不会在这里工作(显然是没有定义的RelativeSource)。

怎么回事?我如何才能使PersonaDataTemplate的情况相关联,如Label的情况那样?

+0

如果你添加一个属性'Self {get {return this; }}'在你的viewmodel上,然后把PhotoView.Persona上的绑定改为'{Binding Self}'?另外..看看这个:http://stackoverflow.com/questions/22595388/binding-usercontrol-inside-a-listview-datatemplate-wpf – mrtig 2014-10-04 15:45:57

+0

@mrtig听起来这样仍然会给我一个参考视图模型,而不是当前绑定到DataTemplate的项目 – fredrik 2014-10-04 15:49:04

+0

是的,我想你是对的。您可以尝试绑定集合的每个成员上的“self”属性。 ..或者你可以尝试'ElementName'建议(在上面的链接中)。 – mrtig 2014-10-04 15:54:49

回答

3

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

在模板项目的情况下,项目背景被设置为模板元素,在这种情况下ViewCell,并递归到ViewCell.ViewStackLayoutPhotoView,内StackLayout和2 Label秒。

FullNameStudentIsAt.Group.Name工作的事实是一个强烈的暗示。

所以,当你说

[...] 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中的上下文。

如果你希望绑定不工作,可能是因为PhotoView莫名其妙定置了BindingContextthis,并防止{Binding}按预期工作,但我不能没有看到PhotoView的代码说。

+0

'PhotoView'确实设置了'BindingContext',但设置了'ViewModel'类。我从那以后删除了ViewModel,然后它就像我期望的那样工作了(就像它为'Label's绑定做的那样)。 – fredrik 2014-10-06 12:30:43

+0

如果你确定答案,接受它。它可能会帮助其他人 – 2014-10-06 19:46:09