项目中有要用到一个ListBox里面多个模板的地方.查了查资料,还真有实现的方法.给出代码:
ps:因为是测试,所以就没有注意命名什么的,大家请原谅
1:MultiTemplatedListBox
继承自ListBox,在PrepareContainerForItemOverride阶段检查数据,以决定选用哪一个模板
1 public class MultiTemplatedListBox : ListBox
2 {
3 public DataTemplate ListItemTemplate1 { get; set; }
4 public DataTemplate ListItemTemplate2 { get; set; }
5
6 public MultiTemplatedListBox() : base() { }
7
8 DataTemplate SelectTemplate(MultiTemplatedListBoxData data)
9 {
10 if (data.TemplateOrder == 1)
11 return ListItemTemplate1;
12 else
13 return ListItemTemplate2;
14 }
15
16 protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
17 {
18 base.PrepareContainerForItemOverride(element, item);
19 ListBoxItem listBoxItem = element as ListBoxItem;
20
21 if (listBoxItem != null)
22 {
23 listBoxItem.ContentTemplate = SelectTemplate((MultiTemplatedListBoxData)item);
24 }
25 }
26 }
2: MultiTemplatedListBoxData 用以决定选用模板的基类
1 public class MultiTemplatedListBoxData
2 {
3 public int TemplateOrder { get; set; }
4 public MultiTemplatedListBoxData()
5 {
6 TemplateOrder = 1;
7 }
8 }
3:测试页面XAML
<lc:MultiTemplatedListBox x:Name="Test">
<lc:MultiTemplatedListBox.ListItemTemplate1>
<DataTemplate>
<Grid Background="Red">
<TextBlock Text="{Binding Name1}"></TextBlock>
</Grid>
</DataTemplate>
</lc:MultiTemplatedListBox.ListItemTemplate1>
<lc:MultiTemplatedListBox.ListItemTemplate2>
<DataTemplate>
<Grid Background="Blue">
<TextBlock Text="{Binding Name2}"></TextBlock>
</Grid>
</DataTemplate>
</lc:MultiTemplatedListBox.ListItemTemplate2>
</lc:MultiTemplatedListBox>
4:测试代码
1 public partial class AATest: PhoneApplicationPage
2 {
3 public AATest()
4 {
5 InitializeComponent();
6 List<MultiTemplatedListBoxData> aa = new List<MultiTemplatedListBoxData>();
7 for (int i = 0; i < 10; i++)
8 {
9 if (i % 2 == 0)
10 aa.Add(new Test1() { TemplateOrder = 1, Name1 = i.ToString() + " Name1!!!" });
11 else
12 aa.Add(new Test2() { TemplateOrder = 2, Name2 = i.ToString() + " Name2!!!" });
13 }
14 this.Test.ItemsSource = aa;
15 }
16 }
17
18 public class Test1 : MultiTemplatedListBoxData
19 {
20 public string Name1 { get; set; }
21 }
22
23 public class Test2 : MultiTemplatedListBoxData
24 {
25 public string Name2 { get; set; }
26 }
测试结果如下: