Highlight whole TreeViewItem line in WPF

前端 未结 9 717
暗喜
暗喜 2020-11-30 17:48

If I set TreeViewItem Background it highlights the header only. How can I highlight the whole line?

I have found a post almost solving a problem http://social.msdn.

9条回答
  •  再見小時候
    2020-11-30 18:45

    Here we go, third times a charm. If you want something that look like this.

    This one takes a bit more work. I'm sure there are many ways of doing this, but this method uses a Length Converter and a TreeViewItem extension method to get the Depth. Both of these are tightly coupled to the TreeViewItem visual tree, so if you start messing with the Templates then you may have troubles. Again, here is the important part, and below is the full code.

    
      
          
      
      
            
                
    
                    
                        
                        
                    
                    
    
                    
                
          
          
        
        
    
    

    TreeViewDepth Extension

    public static class TreeViewItemExtensions
    {
        public static int GetDepth(this TreeViewItem item)
        {
            TreeViewItem parent;
            while ((parent = GetParent(item)) != null)
            {
                return GetDepth(parent) + 1;
            }
            return 0;
        }
    
        private static TreeViewItem GetParent(TreeViewItem item)
        {
            var parent = VisualTreeHelper.GetParent(item);
            while (!(parent is TreeViewItem || parent is TreeView))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
            return parent as TreeViewItem;
        }
    }
    

    LeftMarginMultiplierConverter

    public class LeftMarginMultiplierConverter : IValueConverter
    {
        public double Length { get; set; }
    
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var item = value as TreeViewItem;
            if (item == null)
                return new Thickness(0);
    
            return new Thickness(Length * item.GetDepth(), 0, 0, 0);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }
    

    Control

    
        
        
            
                
                
            
            
        
        
    
    

    Full TreeViewItem Style

    
    
    
    
    
    
    
    
    

提交回复
热议问题