Reputation: 945
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 }
Upvotes: 2
Views: 6924
Reputation: 31
If you have Hierarchical data, this will only work when selecting items at the top level. To select subitems underneath the top level, you have to expand and traverse the tree til the TreeViewItem for the desired item has been created.
See this page for TreeViewExtended
His TreeViewExtended class has a method called SetSelectedItem that actually works!
Upvotes: 1
Reputation: 945
Calling UpdateLayout() prior to get the TreeViewItem does the trick:
private void SelectFistItemInCatTreeView()
{
treeCategories.UpdateLayout();
TreeViewItem item = treeCategories.ItemContainerGenerator.ContainerFromItem(treeCategories.Items[0]) as TreeViewItem;
if (item != null)
{
item.IsSelected = true;
}
}
Upvotes: 3
Reputation: 53155
It looks like the ContainerFromItem method is supposed to be passed the actual item you're binding to, rather than just an tv.Items[0].
I'd look at the following:
Upvotes: 2