How to Expand and collapse WinRTXamlToolkit Treeview programmatically?

473 views Asked by At

Can someone guide me how programmatically expand and collapse the tree and subtrees? I currently do not use a property called IsExpand.

My view

<controls:TreeView ItemTemplate="{StaticResource TreeviewDataTemplate}"
                                   ItemsSource="{Binding TreeItems}" Style="{StaticResource TouchTreeViewStyle}"
                                   HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" ScrollViewer.VerticalScrollBarVisibility="Disabled"/>

Data binding on TreeViewpageViewModel:

 private void BuildTree()
        {
            var tree = BuildChildrenTree(_fullAgendaItems.Where(a => a.PreviousId == null).ToList());
            TreeItems = tree;
        }

and

private ObservableCollection<AgendaItem> BuildChildrenTree(List<AgendaItem> agendaItems)
    {
        var tree = new ObservableCollection<AgendaItem>();
        const string functionName = "BuildChildrenTree";
        try
        {
            //Logs.Write.Entry(ClassName + functionName);
            foreach (var item in agendaItems)
            {
                item.Children =
                    BuildChildrenTree(
                        FullAgendaItems.Where(a => a.PreviousId == item.Id && item.HeadorPaper == 0).ToList());// 

                #region Change bg color of the currently seleted item

                if (_globalSelectedAgendaItem != null && _globalSelectedAgendaItem.Id == item.Id)
                {
                    item.AgendaItemDefaultBg = SelectedColor;
                }

                #endregion

                tree.Add(item);
            }
            //Logs.Write.Success(ClassName + functionName);
        }
        catch (Exception ex)
        {
            Logs.Write.Error(Utility.FmtErrData(ClassName + functionName, ex));
        }
        return tree;
    }
1

There are 1 answers

2
Sunteen Wu On

For TreeView in WinRTXamlToolkit, every TreeViewItem in the TreeView has the IsExpand property. You could get the TreeViewItem you want to expand or collapse code behind and set IsExpand property for it.

To use ContainerFromItem method to get the TreeViewItem by the items you bind to the TreeView, in your code snippet should be AgendaItem.

Suppose your TreeView is named with tvDataBound, the following code snippet will expand the first item.

private void BtnExpand_Click(object sender, RoutedEventArgs e)
{
    TreeViewItem item = (TreeViewItem)tvDataBound.ContainerFromItem(tvDataBound.Items[0]);
    if (!item.IsExpanded)
    {
        item.IsExpanded = true;
    } 
}

By the way, the official sample provide a TreeView you could also reference, it is setting Expand property with TreeViewNode. Also in the insider preview, UWP app provide a TreeView control.