none
Set TreeViewItem visibility from DataTemplate RRS feed

  • Question

  • I would like to set the visibility of a TreeViewItem based on the properties of the bound data. It is easy to hide the data itself, but the child items remain visible because the DataTemplate is hidden - not the entire item.

    Any ideas?
    Tuesday, May 6, 2008 9:02 AM

Answers

  • You can use DataTrigger to implement this type of feature, here is a XAMLPad ready example:

    Code Snippet

    <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Page.Resources>
            <XmlDataProvider x:Key="tree" XPath="*">
                <x:XData>
                    <Products xmlns="">
                        <Product>
                            <Name>Product 1</Name>
                            <ProductID>355</ProductID>
                            <CategoryID>16</CategoryID>
                        </Product>
                        <Product>
                            <Name>Product 2</Name>
                            <ProductID>366</ProductID>
                            <CategoryID>17</CategoryID>
                        </Product>
                    </Products>
                </x:XData>
            </XmlDataProvider>
            
            <HierarchicalDataTemplate ItemsSource="{Binding XPath=child::*}" x:Key="template">
                <TextBlock Name="textBlock" Text="{Binding Path=Name}"/>
            </HierarchicalDataTemplate>
        </Page.Resources>
        <TreeView
            ItemsSource="{Binding Source={StaticResource tree}}"
            ItemTemplate="{StaticResource template}">
            <TreeView.ItemContainerStyle>
                <Style TargetType="{x:Type TreeViewItem}">
                    <Setter Property="IsExpanded" Value="True"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=Name}" Value="Name">
                            <Setter Property="Visibility" Value="Collapsed"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TreeView.ItemContainerStyle>
        </TreeView>
    </Page>


    Hope this helps
    Thursday, May 8, 2008 8:49 AM