首页 > 技术文章 > ItemControl条目类控件使用Index

dongweian 2022-06-19 16:05 原文

在WPF中,为了得到当前ItemsControl的索引,我们可以使用ItemsControl.AlternationIndex附加属性,具体使用为我们先设置所在条目控件的AlternationCount属性为一定数目,然后所在条目控件会自动给每一列按照顺序赋值Index,具体代码如下所示:

 <Window.Resources>
        <x:Array Type="{x:Type system:String}" x:Key="MyArray">
            <system:String>Index-1</system:String>
            <system:String>Index-2</system:String>
            <system:String>Index-3</system:String>
        </x:Array>
    </Window.Resources>
    <ItemsControl ItemsSource="{StaticResource MyArray}" AlternationCount="100" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
               <StackPanel Orientation="Horizontal">
                   <TextBlock Text="{Binding Path=(ItemsControl.AlternationIndex), 
                    RelativeSource={RelativeSource TemplatedParent}, 
                    StringFormat={}Index is {0}:}">
                   </TextBlock>
                   <TextBlock Text="{Binding}"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl >

实际运行效果如下图所示:

image-20220619160418044

推荐阅读