2016-12-09 30 views
0

我想爲Xamarin.Forms中的ListView創建一個自定義模板。在模板內部,我放置了一個名爲「MainTemplate」的屬性的自定義視圖,其輸入也是一個模板。問題是,如果MainTemplate包含一個或多個DataBindings,它們將被忽略(所有的XAML都被加載,但綁定的數據會被忽略)。伊爾看起來像我的模板內的範圍會丟失。從視圖到其他視圖的數據綁定

ListView控件:

 <ListView ItemsSource="{Binding items}"> 
     <ListView.ItemTemplate> 
      <DataTemplate> 
       <ViewCell> 
        <StackLayout> 
         <c:GestureListItem> 
          <c:GestureListItem.MainTemplate> 
           <ContentView BackgroundColor="Red" Padding="10"> 
            <Label Text="{Binding Name}" /> 
           </ContentView> 
          </c:GestureListItem.MainTemplate> 
         </c:GestureListItem> 
        </StackLayout> 
       </ViewCell> 
      </DataTemplate> 
     </ListView.ItemTemplate> 
    </ListView> 

我自定義模板:

<?xml version="1.0" encoding="UTF-8"?> 
<Grid xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Xamtools.GestureListItem"> 
    <ContentView Content="{Binding MainTemplate}" x:Name="mainTemplate" /> 
</Grid> 

...和其背後的代碼:

public partial class GestureListItem : Grid 
{ 
    public static readonly BindableProperty MainTemplateProperty = BindableProperty.Create("MainTemplate", typeof(View), typeof(GestureListItem), null, propertyChanged: MainTemplatePropertyChanged); 
    private static void MainTemplatePropertyChanged(BindableObject bindable, object oldValue, object newValue) 
    { 
     var ob = bindable as GestureListItem; 
     ob.MainTemplate = (View)newValue; 
    } 

    public View MainTemplate { set { SetValue(MainTemplateProperty, value); } get { return (View)GetValue(MainTemplateProperty); } } 
    public GestureListItem() 
    { 
     InitializeComponent(); 
     this.mainTemplate.BindingContext = this; 
    } 
} 

回答