我有問題在Silverlight中的TreeView中選擇第一個TreeViewItem。以下代碼只是在方法SelectFistItemInCatTreeView中給出了一個空值。爲什麼?有任何想法嗎?如何在Silverlight Treeview中選擇一個項目?
<controls:TreeView x:Name="treeCategories" Grid.Column="1" Grid.Row="2" SelectedItemChanged="treeCategories_SelectedItemChanged">
<controls:TreeView.ItemTemplate>
<common:HierarchicalDataTemplate ItemsSource="{Binding SubCats}">
<StackPanel >
<TextBlock Text="{Binding Name}"></TextBlock>
</StackPanel>
</common:HierarchicalDataTemplate>
</controls:TreeView.ItemTemplate>
</controls:TreeView>
1 public MainPage()
2 {
3 InitializeComponent();
4
5 DBService.DocTrackingServeceClient webService = new DockTracking.DBService.DocTrackingServeceClient();
6 webService.GetDocCategoriesCompleted += new EventHandler(webService_GetDocCategoriesCompleted);
7 webService.GetDocCategoriesAsync();
8 treeCategories.Loaded += new RoutedEventHandler(treeCategories_Loaded);
9 }
10
11 void webService_GetDocCategoriesCompleted(object sender, DockTracking.DBService.GetDocCategoriesCompletedEventArgs e)
12 {
13
14 List cats = new List();
15 cats = GetCats(e.Result.ToList(), null);
16 treeCategories.ItemsSource = cats;
17 }
18
19 void treeCategories_Loaded(object sender, RoutedEventArgs e)
20 {
21 SelectFistItemInCatTreeView();
22 }
23
24 private void SelectFistItemInCatTreeView()
25 {
26 TreeViewItem item = treeCategories.ItemContainerGenerator.ContainerFromItem(treeCategories.Items[0]) as TreeViewItem;
27 if (item != null)
28 {
29 item.IsSelected = true;
30 }
31 }
我試過SetSelectedItem方法,但它不適合我。無論如何,關於treeview的文章非常棒,並且在其他情況下幫助我。 – 2010-05-05 13:06:08
鏈接不再有效。謝謝微軟搞亂所有silverlight資源鏈接。 – Entrodus 2012-11-13 14:33:30