How to Update TreeViewItem's IsExpanded property to false in code behind?

I am working with WPF TreeView control. I am creating a hierarchical data structure and assigning it to ItemsSource and it will generate TreeviewItems automatically. By default I use IsExpanded of TreeViewItem to true. But in a particular case, I want to set IsExpanded property to false. So that treeview loading doesn't take time to generate all items. How can I set that in code since I don't have reference to TreeViewItem's instance at that time?


I am looking for a way so that I can set all TreeViewItem's default behaviour in my TreeView to collapsed while doing a specific operation and set back to Expanded when this operation completes.


IsExpanded defaults to false, so I assume you have a Style changing the default to true. If you change this Style to use a Binding (and change the value during your "specific operation") then the TreeViewItems without an explicitly set IsExpanded will default to false instead:

<Grid xmlns="" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="">
        <CheckBox x:Name="chkDefaultExpanded" Content="Default Expanded"/>
                <Style TargetType="TreeViewItem">
                    <Setter Property="IsExpanded" Value="{Binding ElementName=chkDefaultExpanded, Path=IsChecked}"/>
            <TreeViewItem Header="Do">
                <TreeViewItem Header="A">
                    <TreeViewItem Header="1"/>
                    <TreeViewItem Header="2"/>
                    <TreeViewItem Header="3"/>
                <TreeViewItem Header="B"/>
                <TreeViewItem Header="C"/>
            <TreeViewItem Header="Re">
                <TreeViewItem Header="D">
                    <TreeViewItem Header="4"/>
                    <TreeViewItem Header="5"/>
                    <TreeViewItem Header="6"/>
                <TreeViewItem Header="E"/>
                <TreeViewItem Header="F"/>

A way to do this is to use a ViewModel, i.e. an abstraction of the UI, based on the model (the data). If you include a bool property (e.g. IsExpanded) in the part of the ViewModel related to the tree data, you can bind the TreeViewItem's IsExpanded property to the IsExpanded property of the ViewModel. The view is bound to the ViewModel which includes a copy or a reference of the Model.

Then, expanding or collapsing parts of the tree gets to be as simple as updating the ViewModel (which needs to implement INotifyPropertyChanged or define Dependency properties).

Need Your Help

Read Data From Excel C#

c# excel

This question is only to get some idea how it would be better to implement some functionality.

storing the selected date on bootstrap 3 date time picker with meteor

javascript jquery twitter-bootstrap date meteor

I am using bootstrap 3 date time picker in a meteor application. I am trying to store the selected date so I can use it later. Currently just trying to show the selected date in console. When I run...