Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding TreeView items

Tags:

c#

wpf

treeview

I've been trying to just hide items from a TreeView. I'm using a custom data type as source (called SettingsMenuItem) which inherits from FrameworkElement (currently FrameworkContentElement, because otherwise the TreeView renders them wrong).

My goal is by setting the VisibilityProperty of these FrameworkElements to either Collapsed or Visible that I'm able to hide certain items (including their children). I know that this can be done by deleting items from the source collection. But that's not what I want. It would mean that I have to mirror each collection in order to keep track of it's actual items, bind to each one in order to be notified about Visibility-changes and create a new collection each time one changes. A lot of overhead for this.

Right now I have no clue how I could accomplish that. I figure it's related to the ItemsGenerator, but I haven't seen any possibility to override it's behaviour. I thought TreeView would be able to detect Visibility, but obviously it doesn't. As alternative I thought of a custom TreeViewItem (maybe even TreeView if necessary) - but at this point the abstraction of this whole system overwhelms me. I don't know where to start and what is actually necessary to solve the problem.

Tips what I have to change or implement by myself would be more than enough. A complete solution would be nice.

like image 697
SharpShade Avatar asked Sep 20 '15 21:09

SharpShade


1 Answers

You can do this using a data trigger bound to a property (e.g. "IsVisible") in you tree data nodes:

<TreeView.ItemContainerStyle>
    <Style TargetType="{x:Type TreeViewItem}">
        <Setter Property="Visibility" Value="Visible" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsVisible}" Value="False">
                <Setter Property="Visibility" Value="Collapsed" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TreeView.ItemContainerStyle>

While this technically answers your question I would be wary of actually doing it. User3690202's comment is correct, it's the sort of thing you would normally do via filtering in your view model.

like image 72
Mark Feldman Avatar answered Oct 04 '22 22:10

Mark Feldman