WPF TreeViewItem Toggle Button visibility

六月ゝ 毕业季﹏ 提交于 2019-12-19 19:57:25

问题


I've ran into an issue I'm hoping someone can help me solve. I've run into a case where my nodes contain a set of child nodes with visibility set to false. I'm hoping that I can disable the toggle arrow beside the TreeViewItem if all it's children are invisibile. Is this possible? Here's an example:

<TreeView Margin="10,10,0,13" Name="TreeView1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="194" Height="200">
    <TreeViewItem Header="Cold Drinks">
        <TreeViewItem Header="Coke" Visibility="False"></TreeViewItem>
        <TreeViewItem Header="Pepsi" Visibility="False"></TreeViewItem>
    </TreeViewItem>
</TreeView>

How would i get the Cold Drinks TreeViewItem to hide the toggle arrow?


回答1:


If you see the deafult controlTemplate of TreeViewItem, you will see that visibility of Toggle button is bound to ItemsControl.HasItems. Trigger look like this -

<Trigger Property="ItemsControl.HasItems">
  <Setter TargetName="Expander" Property="UIElement.Visibility" Value="{x:Static Visibility.Hidden}" />
     <Trigger.Value>
        <s:Boolean>False</s:Boolean>
     </Trigger.Value>
</Trigger>

So, as a workaround, you can create your own Custom Control derived from TabItem and bind your HasItems with your own CLR property which will loop through all your childItems(TreeViewItems) and will return True if any of the Item is visible or False if all items are hidden/collapsed state. That way your toggle button will automatically will hide as per Trigger.

In case you want to know how to create Custom control and bind it to your CLR property, you can refer to this -

WPF TreeView databinding to hide/show expand/collapse icon

This is somewhat same what you has been looking for. Hope this helps..




回答2:


Both internally (i.e. for keyboard navigation) and in its default template the TreeViewItem is relying on its HasItems property to know if it has children or not. You will likely need to set the ItemsSource of the TreeViewItem to a list and filter out the collapsed items.



来源:https://stackoverflow.com/questions/7905881/wpf-treeviewitem-toggle-button-visibility

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!