如何在Silverlight Treeview中选择一个项目?

时间:2009-09-08 15:08:28

标签: silverlight treeview

我在Silverlight中的TreeView中选择第一个TreeViewItem时遇到问题。以下代码仅在方法SelectFistItemInCatTreeView中提供null值。为什么?有什么想法吗?

<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 个答案:

答案 0 :(得分:3)

在获取TreeViewItem之前调用UpdateLayout()可以解决问题:

private void SelectFistItemInCatTreeView()
{

  treeCategories.UpdateLayout();

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

答案 1 :(得分:2)

看起来ContainerFromItem方法应该传递给你绑定的实际项目,而不仅仅是一个tv.Items [0]。

我会看以下内容:

答案 2 :(得分:1)

如果您有分层数据,则仅在顶层选择项目时才有效。 要选择顶层下面的子项,您必须展开并遍历树,直到创建了所需项目的TreeViewItem。

See this page for TreeViewExtended

他的TreeViewExtended类有一个名为SetSelectedItem的方法,它实际上有效!