在Silverlight中如何使用TreeView显示分层数据?我这里用一个简单的例子:
后台代码: public partial class MainPage : UserControl { static public ObservableCollection<Topic> Topics = new ObservableCollection<Topic>(); public MainPage() { InitializeComponent(); Topics.Add(new Topic("Using Controls and Dialog Boxes", -1)); Topics.Add(new Topic("Getting Started with Controls", 1)); Topic DataGridTopic = new Topic("DataGrid", 4); DataGridTopic.ChildTopics.Add( new Topic("Default Keyboard and Mouse Behavior in the DataGrid Control", -1)); DataGridTopic.ChildTopics.Add( new Topic("How to: Add a DataGrid Control to a Page", -1)); DataGridTopic.ChildTopics.Add( new Topic("How to: Display and Configure Row Details in the DataGrid Control", 1)); Topics.Add(DataGridTopic); myTreeView.DataContext = Topics; } } public class Topic { public string Title { get; set; } public int Rating { get; set; } private ObservableCollection<Topic> childTopicsValue = new ObservableCollection<Topic>(); public ObservableCollection<Topic> ChildTopics { get { return childTopicsValue; } set { childTopicsValue = value; } } public Topic() {} public Topic(string title, int rating) { Title = title; Rating = rating; } }
前台页面代码: <StackPanel x:Name="LayoutRoot" Background="White"> <StackPanel.Resources> <sdk:HierarchicalDataTemplate x:Key="ChildTemplate" > <TextBlock FontStyle="Italic" Text="{Binding Path=Title}" /> </sdk:HierarchicalDataTemplate> <sdk:HierarchicalDataTemplate x:Key="NameTemplate" ItemsSource="{Binding Path=ChildTopics}" ItemTemplate="{StaticResource ChildTemplate}"> <TextBlock Text="{Binding Path=Title}" FontWeight="Bold" /> </sdk:HierarchicalDataTemplate> </StackPanel.Resources> <sdk:TreeView Width="400" Height="300" ItemsSource="{Binding}" ItemTemplate="{StaticResource NameTemplate}" x:Name="myTreeView" /> </StackPanel>
本站技术原创栏目文章均为中睿原创或编译,转载请注明:文章来自中睿,本站保留追究责任的权利。