我正在编写我的Windows Phone 8应用程序,它使用LongListSelector来显示一些数据.
如何为LongListSelector中的第一个和最后一个项设置不同的项模板?
基本上我只想在每个项目中显示相同的信息,但在最后和第一项中使用很少的不同项目“布局”.
您可以实现某种数据模板选择器,以帮助确定基于索引选择哪个模板.您可以从创建可重用的抽象TemplateSelector类开始.我使用了
Implementing Windows Phone 7 DataTemplateSelector and CustomDataTemplateSelector中解释的许多想法,但修改了实现以允许选择基于索引的模板.
原文链接:https://www.f2er.com/windows/371672.htmlpublic abstract class TemplateSelector : ContentControl { public abstract DataTemplate SelectTemplate(object item,int index,int totalCount,DependencyObject container); protected override void OnContentChanged(object oldContent,object newContent) { base.OnContentChanged(oldContent,newContent); var parent = GetParentByType<LongListSelector>(this); var index = parent.ItemsSource.IndexOf(newContent); var totalCount = parent.ItemsSource.Count; ContentTemplate = SelectTemplate(newContent,index,totalCount,this); } private static T GetParentByType<T>(DependencyObject element) where T : FrameworkElement { T result = null; DependencyObject parent = VisualTreeHelper.GetParent(element); while (parent != null) { result = parent as T; if (result != null) { return result; } parent = VisualTreeHelper.GetParent(parent); } return null; } }
拥有该类后,您可以添加自己的数据模板选择器逻辑.在你的情况下,可能是这样的
public class MyTemplateSelector : TemplateSelector { public DataTemplate First { get; set; } public DataTemplate Default { get; set; } public DataTemplate Last { get; set; } public override DataTemplate SelectTemplate(object item,DependencyObject container) { if (index == 0) return First; else if (index == totalCount-1) return Last; else return Default; } }
最后是Xaml
<phone:PhoneApplicationPage.Resources> <DataTemplate x:Key="first"> <TextBlock Text="{Binding Name}" Foreground="Yellow" /> </DataTemplate> <DataTemplate x:Key="default"> <TextBlock Text="{Binding Name}" /> </DataTemplate> <DataTemplate x:Key="last"> <TextBlock Text="{Binding Name}" Foreground="Red" /> </DataTemplate> <DataTemplate x:Key="SelectingTemplate"> <local:MyTemplateSelector Content="{Binding}" First="{StaticResource first}" Default="{StaticResource default}" Last="{StaticResource last}" HorizontalContentAlignment="Stretch" /> </DataTemplate> </phone:PhoneApplicationPage.Resources> <phone:LongListSelector ItemTemplate="{StaticResource SelectingTemplate}" ItemsSource="{Binding Data}" />