How do I select an item in a Silverlight Treeview?
I am having trouble selecting the first TreeViewItem in a TreeView in Silverlight. The following code just gives a null value in the SelectFistItemInCatTreeView method. What for? 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 }
+2
source to share
3 answers
Calling UpdateLayout () before getting 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;
}
}
+3
source to share
It looks like the ContainerFromItem method should be passing the actual object you are binding to, not just tv.Items [0].
I would look at the following:
- Post by Justin Josef-Angel about using ContainerFromItem method
- Previous SO question about selecting a TreeViewItem in code
+2
source to share
If you have Hierarchical data, this will only work when you select items at the top level. To select subitems below the top level, you must expand and traverse the tree until the TreeViewItem is created for the desired item.
See this page for TreeViewExtended
Its TreeViewExtended class has a SetSelectedItem method that actually works!
+1
source to share