2009-09-08 68 views
2

我有問題在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   } 

回答

3

調用UpdateLayout請()來獲得樹型視圖之前訣竅:

private void SelectFistItemInCatTreeView() 
{ 

    treeCategories.UpdateLayout(); 

    TreeViewItem item = treeCategories.ItemContainerGenerator.ContainerFromItem(treeCategories.Items[0]) as TreeViewItem; 
    if (item != null) 
    { 
    item.IsSelected = true; 
    } 
} 
1

如果您有分層數據,則只有在選擇頂層的項目時才能使用。 要選擇頂層下面的子項目,必須展開並遍歷樹,直到已創建所需項目的TreeViewItem。

See this page for TreeViewExtended

他TreeViewExtended類有一個方法叫SetSelectedItem實際工作!

+0

我試過SetSelectedItem方法,但它不適合我。無論如何,關於treeview的文章非常棒,並且在其他情況下幫助我。 – 2010-05-05 13:06:08

+0

鏈接不再有效。謝謝微軟搞亂所有silverlight資源鏈接。 – Entrodus 2012-11-13 14:33:30

相關問題