tags:

views:

172

answers:

2

Hi I have a treeview control and all the nodes populated from xml. The tree has 5 elements in the first level and each contains several elements in level 2. My requirmrnt is only first element should be expanded when the startup of my application. I have written the method like this

public void SelectAndExpand(ItemsControl ParentContainer)
    {
        TreeViewItem CurrentContainer = (TreeViewItem)ParentContainer.ItemContainerGenerator.ContainerFromIndex(0);
        if (CurrentContainer == null)
        {
            return;
        }
        CurrentContainer.IsExpanded = true;
        CurrentContainer.UpdateLayout();

        TreeViewItem ChildItem = (TreeViewItem)CurrentContainer.ItemContainerGenerator.ContainerFromIndex(0);
        if (ChildItem != null)
        {
            ChildItem.IsSelected = true;
            CurrentContainer.UpdateLayout();
        }
    }

and I called this method like this

public Window1()
    {            
        InitializeComponent();
        SelectAndExpand(MyTree);
    }

But this doesn't work...

any suggestions to overcome this problem

Thanks

A: 

You can define the ItemContainerStyle so that the items are expanded :

<TreeView>
  <TreeView.ItemContainerStyle>
    <Style TargetType="{x:Type TreeViewItem}">
      <Setter Property="IsExpanded" Value="True"/>
    </Style>
  </TreeView.ItemContainerStyle>

  ...
</TreeView>
Thomas Levesque
A: 

Thanks Thomas

I could overcome this problem by other way...

I set the Loaded event as

Loaded="MyTree_Loaded"

I handeld as

private void MyTree_Loaded(object sender, RoutedEventArgs e)
    {
        TreeViewItem CurrentContainer = (TreeViewItem)MyTree.ItemContainerGenerator.ContainerFromIndex(0);
        if (CurrentContainer == null)
        {
            return;
        }
        CurrentContainer.IsExpanded = true;
        CurrentContainer.UpdateLayout();

        TreeViewItem ChildItem = (TreeViewItem)CurrentContainer.ItemContainerGenerator.ContainerFromIndex(0);
        if (ChildItem != null)
        {
            ChildItem.IsSelected = true;
            CurrentContainer.UpdateLayout();                
        }            
    }

Thanks