#目的
实现tree效果。
#前提条件
需要区分WP7.0和WP7.1+版本。
对于WP7.0版本,可采用Listbox嵌套listbox方法实现;
对于WP7.1+(Mango)版本,则多一项选择,采用系统的toolkit方法,即ExpanderView实现。
#实现过程
本文目前采用listbox嵌套方法实现。(demo,有bug。。。)
1.无需声明命名空间。
2.demo.xaml中使用如下代码:
<!--ContentPanel - tree with item and sub item-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="4,4,4,4">
<ListBox x:Name="MainList">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel >
<TextBlock Text="{Binding Name}" MouseLeftButtonDown="Text_MouseLeftButtonDown" FontSize="40"></TextBlock>
<ListBox Visibility="Collapsed" ItemsSource="{Binding Chapters}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="5">
<TextBlock Text="{Binding Title}" FontSize="30">
</TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
3.在demo.xaml.cs中使用如下代码:
声明控件使用:
using System.Collections.ObjectModel;
代码实现:
public treeListPage()
{
InitializeComponent();
ObservableCollection<Book> books = new ObservableCollection<Book>();
for (int i = 0; i < 10; i++)
{
Book book = new Book { Name = "Book" + i.ToString()};
book.Chapters = new List<Chapter>();
for (int j = 0; j < 10; j++)
book.Chapters.Add(new Chapter { Title = "Chapter" + i.ToString() + "_" + j.ToString()});
books.Add(book);
}
this.MainList.ItemsSource = books;
}
public class Book
{
public string Name { get; set; }
public List<Chapter> Chapters { get; set; }
}
public class Chapter
{
public string Title{get;set;}
public string Page{get;set;}
}
private void Text_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
TextBlock t = sender as TextBlock;
StackPanel p = VisualTreeHelper.GetParent(t) as StackPanel;
ListBox sublist = p.Children[1] as ListBox;
if (sublist.Visibility == Visibility.Collapsed)
sublist.Visibility = Visibility.Visible;
else
sublist.Visibility = Visibility.Collapsed;
}
private void Text_MouseLeftButtonDown2(object sender, MouseButtonEventArgs e)
{
}
#效果
#遗留问题
1.目前在Chapter*上点住时,无法响应拖动事件。
2.打开Book目录时,有时不能将当前打开的作为展现页面呈现出来。