通常我在App.xaml,ContentPage.xaml或View.xaml级别内定义datatemplate。是否可以在单独的xaml文件中定义datatemplate,以便我可以为代码中的视图分配datatemplate
if (Device.Idiom == TargetIdiom.Phone)
childListView.ItemTemplate = (DataTemplate)Resources["phoneSignInTemplate"];
else if (Device.Idiom == TargetIdiom.Tablet)
childListView.ItemTemplate = (DataTemplate)Resources["tabletSignInTemplate"];
如果我在App.xaml或ContentPage或Views级别放置太多datatemplate。我担心它会在加载页面时影响性能。
答案 0 :(得分:0)
您可以在xaml中生成新的ViewCell并将它们用作DataTemplates:
MyTextViewCell.xaml:
<?xml version="1.0" encoding="UTF-8"?>
<ViewCell
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XFTests.MyTextViewCell">
<ViewCell.View>
<StackLayout>
<Label
Text="Not a phone" />
<Label Text="{Binding .}" />
</StackLayout>
</ViewCell.View>
</ViewCell>
MyTextViewCellPhone.xaml:
<?xml version="1.0" encoding="UTF-8"?>
<ViewCell
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XFTests.MyTextViewCellPhone">
<ViewCell.View>
<StackLayout>
<Label
Text="Phone" />
<Label Text="{Binding .}" />
</StackLayout>
</ViewCell.View>
</ViewCell>
然后将您需要的那个分配给项目模板。
ListView listView = new ListView
{
ItemsSource = new string[] { "Max", "John" }
};
if (Device.Idiom == TargetIdiom.Phone)
listView.ItemTemplate = new DataTemplate(typeof(MyTextViewCellPhone));
else
listView.ItemTemplate = new DataTemplate(typeof(MyTextViewCell));