jsiva
jsiva

Reputation:

Expanded TreeView

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

Upvotes: 1

Views: 1771

Answers (3)

JoanComasFdz
JoanComasFdz

Reputation: 3066

Another way is to follow this article Simplifying the WPF TreeView by Using the ViewModel Pattern, and the load the xml to the ViewModel classes.

You can set the IsExpanded property directly in the codebehind without interacting with the TreeView.

Upvotes: 0

jsiva
jsiva

Reputation:

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

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292405

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>

Upvotes: 1

Related Questions