【问题标题】:UWP Different styles for odd and even elements ListBoxItemUWP 奇偶元素不同样式 ListBoxItem
【发布时间】:2020-09-24 07:33:48
【问题描述】:

我需要为奇数和偶数元素 ListBoxItem 设置不同的背景。我找到了一个可以解决我的问题的代码,但它不想在 UWP 中工作:

<Trigger Property="ItemsControl.AlternationIndex" Value="1">
    <Setter Property="Background" Value="Orange"/>
</Trigger>

是否有任何与 ItemsControl.AlternationIndex 属性类似的东西,或者如何在 VisualState 中指定偶数和奇数元素的样式?

提前感谢您的回复。

【问题讨论】:

    标签: c# uwp listboxitem visualstatemanager


    【解决方案1】:

    目前在 UWP 中,ListBox 不提供设置替代行背景的相关属性。

    我们可以创建一个CustomListBox 作为ListBox 的派生类来满足我们的需求。

    public class CustomListBox : ListBox
    {
        public Brush AlternativeBackground
        {
            get { return (Brush)GetValue(AlternativeBackgroundProperty); }
            set { SetValue(AlternativeBackgroundProperty, value); }
        }
    
        public static readonly DependencyProperty AlternativeBackgroundProperty =
            DependencyProperty.Register("AlternativeBackground", typeof(Brush), typeof(CustomListBox), new PropertyMetadata(null));
    
    
        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);
            var listBoxItem = element as ListBoxItem;
            if (listBoxItem != null)
            {
                var index = IndexFromContainer(element);
    
                if ((index + 1) % 2 != 1)
                {
                    listBoxItem.Background = AlternativeBackground;
                }
            }
        }
    }
    

    用法

    <local:CustomListBox AlternativeBackground="Orange">
        <ListBoxItem>Item 1</ListBoxItem>
        <ListBoxItem>Item 2</ListBoxItem>
        <ListBoxItem>Item 3</ListBoxItem>
        <ListBoxItem>Item 4</ListBoxItem>
    </local:CustomListBox>
    

    【讨论】:

      【解决方案2】:

      您可以使用Microsoft.Toolkit.Uwp.UI.Extensions,它可以帮助您设置AlternateColor & AlternateItemTemplate。 更多信息,您可以下载Windows Community Toolkit

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-02
        • 2011-07-03
        • 1970-01-01
        • 1970-01-01
        • 2011-02-05
        • 2012-10-01
        • 1970-01-01
        • 2014-01-17
        相关资源
        最近更新 更多