HierarchicalDataTemplate and HeaderedItemsControl with ControlTemplate fails to show nested data

前端 未结 3 1923
忘了有多久
忘了有多久 2021-02-11 07:13

I can get this pattern to work with Menu and TreeView but I must be missing something when I make an attempt with HeaderedItemsControl:

3条回答
  •  青春惊慌失措
    2021-02-11 07:29

    Here is a late answer. Been trying to figure this out as well, but was not satisfied with the reasoning in the above answer and/or the linked answer, as the XAML pattern should be the same between all controls.

    After a bit of time with jetbrains dotPeek, and combing thought the TreeView Control the answer is finally quite simple. The TreeView and TreeViewItem override IsItemItsOwnContainerOverride and GetContainerForItemOverride to the control which will hold the children (TreeViewItem in the TreeView Case). You can create two simple custom controls to handle this.

    Your HeaderedItemControl class would be something like this:

    public class MyHierarchicalViewItem : HeaderedItemsControl
    {
        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return item is MyHierarchicalViewItem;
        }
    
        protected override DependencyObject GetContainerForItemOverride()
        {
            return (DependencyObject)new MyHierarchicalViewItem();
        }
    }
    

    Your ItemControl (Equivalent to the TreeView or Menu) would be this:

    public class MyHierarchicalView:ItemsControl 
    {
        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return item is MyHierarchicalViewItem;
        }
    
        protected override DependencyObject GetContainerForItemOverride()
        {
    
            return (DependencyObject) new MyHierarchicalViewItem();
        }
    }
    

    Your XAML would be largely the same, just putting referencing the correct control and adding the appropriate namespace (my case xmlns:myControls="clr-namespace:").

    
    
            
                
            
    
            
    
            
                
                    
                        
                            
                            
                            
                        
                        
                            
                            
                        
                    
                
            
    
            
    
        
            
            
        
    
    
    

提交回复
热议问题