如何设置使ListBox中第一项ListBoxItem和最后一项ListBoxItem显示效果上与其他的ListBoxItem有所不同? RRS feed

  • 问题

  • 如题所示



    2019年2月21日 11:01


  • Hello,

    请问你的项目是WPF吗? 如果是的话,你可以采纳一下下面的建议。

    如果你想使ListBox的第一项和最后一项显示的效果和其他项不一样的话, 那你可以使用Converter去判断是否是第一项或者最后一项。

     class IsLastItemInContainerConverter:IValueConverter
            public object Convert(object value, Type targetType,
                             object parameter, CultureInfo culture)
                DependencyObject item = (DependencyObject)value;
                ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(item);
                Int32 index = ic.ItemContainerGenerator.IndexFromContainer(item);
                Int32 lastindex = ic.Items.Count - 1;
                if(index==0 || index==lastindex)
                    return true;
                return false;
                //return ic.ItemContainerGenerator.IndexFromContainer(item)
                        //== ic.Items.Count - 1;
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
                throw new NotImplementedException();
            <converter:IsLastItemInContainerConverter x:Key="IsLastItemInContainerConverter" />
            <Style x:Key="ColorsItemStyle" TargetType="ListBoxItem">
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource IsLastItemInContainerConverter}}" Value="True">
                        <Setter Property="Foreground" Value="Red"/>
                ItemContainerStyle="{StaticResource ColorsItemStyle}"
                ItemsSource="{Binding models}">
                        <TextBlock Text="{Binding field}" />
     public partial class Window17 : Window
            public ObservableCollection<model> models { get; set; }            
            public Window17()
                models = new ObservableCollection<model>()
                    new model(){field="test1"},
                    new model(){field="test2"},
                    new model(){field="test3"},
                    new model(){field="test4"}
                this.DataContext = this;
        public class model
            public string field { get; set; }

    Best Regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    2019年2月22日 8:30