I am having problems to select the first TreeViewItem in a TreeView in Silverlight. The following code just gives a null value in the method SelectFistItemInCatTreeView. Why? Any ideas?
<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 }