WPF: Alternating colors on a ItemsControl?

后端 未结 3 942
無奈伤痛
無奈伤痛 2020-12-06 04:07

How do I get alternating colors on a ItemsControl? I have AlternationCount set to 2, but the ItemsControl.AlternationIndex property always returns 0.

                


        
3条回答
  •  天涯浪人
    2020-12-06 04:47

    If you don't want to use the DataTemplate approach, you can create a custom control that uses a ContentControl as the item container, therefore allowing you to specify a background color.

    Class:

    public class ItemsControlAlternating : ItemsControl
    {
        static ItemsControlAlternating()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ItemsControlAlternating),
                     new FrameworkPropertyMetadata(typeof(ItemsControlAlternating)));
        }
    
        protected override DependencyObject GetContainerForItemOverride()
        {
            return new ContentControl();
        }
    
        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return item is ContentControl;
        }
    }
    

    Resource Dictionary:

    
           
       
    
    

提交回复
热议问题