开发者

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?

Edit:

I am looking for a way so that I can set all TreeViewItem's default behaviour in my TreeView to collapsed while doing a specif开发者_C百科ic 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="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <CheckBox x:Name="chkDefaultExpanded" Content="Default Expanded"/>
        <TreeView>
            <TreeView.Resources>
                <Style TargetType="TreeViewItem">
                    <Setter Property="IsExpanded" Value="{Binding ElementName=chkDefaultExpanded, Path=IsChecked}"/>
                </Style>
            </TreeView.Resources>
            <TreeViewItem Header="Do">
                <TreeViewItem Header="A">
                    <TreeViewItem Header="1"/>
                    <TreeViewItem Header="2"/>
                    <TreeViewItem Header="3"/>
                </TreeViewItem>
                <TreeViewItem Header="B"/>
                <TreeViewItem Header="C"/>
            </TreeViewItem>
            <TreeViewItem Header="Re">
                <TreeViewItem Header="D">
                    <TreeViewItem Header="4"/>
                    <TreeViewItem Header="5"/>
                    <TreeViewItem Header="6"/>
                </TreeViewItem>
                <TreeViewItem Header="E"/>
                <TreeViewItem Header="F"/>
            </TreeViewItem>
        </TreeView>
    </StackPanel>
</Grid>


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜