2014-10-04 117 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