实现ListView动态加载不同的数据模板需要用到DataTemplateSelector
public class DynamicTemplateSelector: DataTemplateSelector
{
public DataTemplate TextTemplate { set; get; }
public DataTemplate PickerTemplate { set; get; }
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
var model = item as ItemModel;
if (model.DataType == 1)
return TextTemplate;
else
return PickerTemplate;
}
}
public class ItemModel
{
public string Label { set; get; }
public string Value { set; get; }
public int DataType { set; get; }
}
UI数据绑定
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:XamarinApp"
xmlns:c="clr-namespace:XamarinApp.Controls"
x:Class="XamarinApp.MainPage">
<ContentPage.Resources>
<DataTemplate x:Key="textTemplate">
<ViewCell>
<StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="FillAndExpand">
<Label Text="{Binding Label}" VerticalOptions="Center"/>
<Entry Text="{Binding Value}" Margin="10,0" HorizontalOptions="FillAndExpand"/>
</StackLayout>
</ViewCell>
</DataTemplate>
<DataTemplate x:Key="pickertTemplate">
<ViewCell>
<StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="FillAndExpand">
<Label Text="{Binding Label}" VerticalOptions="Center"/>
<Picker SelectedItem="{Binding Value,Mode=TwoWay}" Margin="10,0" HorizontalOptions="FillAndExpand">
<Picker.Items>
<x:String>男</x:String>
<x:String>女</x:String>
</Picker.Items>
</Picker>
</StackLayout>
</ViewCell>
</DataTemplate>
<c:DynamicTemplateSelector x:Key="dynamicTemplate" TextTemplate="{StaticResource textTemplate}" PickerTemplate="{StaticResource pickertTemplate}">
</c:DynamicTemplateSelector>
</ContentPage.Resources>
<StackLayout>
<ListView ItemsSource="{Binding Items}" ItemTemplate="{StaticResource dynamicTemplate}" Margin="15,20">
</ListView>
</StackLayout>
</ContentPage>
public partial class MainPage : ContentPage
{
private List<ItemModel> items;
public List<ItemModel> Items
{
get
{
return items;
}
set
{
items = value;
}
}
public MainPage()
{
InitializeComponent();
Items = new List<ItemModel>();
Items.Add(new ItemModel() {DataType=1, Label="姓名",Value="" });
Items.Add(new ItemModel() { DataType = 2, Label = "性别", Value = "男" });
this.BindingContext = this;
}
}
用起来就是这么简单,噢耶!