【发布时间】:2016-12-09 19:56:56
【问题描述】:
我正在尝试为 Xamarin.Forms 中的 ListView 创建自定义模板。在模板中,我放置了一个自定义视图,该视图具有一个名为“MainTemplate”的属性,其输入也是一个模板。问题在于,如果 MainTemplate 包含一个或多个 DataBinding,它们将被忽略(所有 XAML 都已加载,但绑定的数据会被跳过)。我看起来好像在我的模板中范围丢失了。
列表视图:
<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;
}
}
【问题讨论】:
标签: c# xamarin data-binding xamarin.forms