编号列表框

Wal*_*mer 24 c# wpf listbox

我有一个已排序的列表框,需要显示每个项目的行号.在这个演示中,我有一个带有Name字符串属性的Person类.列表框显示按名称排序的人员列表.如何添加到列表框的datatemplate行号?

XAML:

<Window x:Class="NumberedListBox.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <ListBox 
        ItemsSource="{Binding Path=PersonsListCollectionView}" 
        HorizontalContentAlignment="Stretch">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Name}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>
Run Code Online (Sandbox Code Playgroud)

代码背后:

using System;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.Windows;
using System.ComponentModel;

namespace NumberedListBox
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            Persons = new ObservableCollection<Person>();
            Persons.Add(new Person() { Name = "Sally"});
            Persons.Add(new Person() { Name = "Bob" });
            Persons.Add(new Person() { Name = "Joe" });
            Persons.Add(new Person() { Name = "Mary" });

            PersonsListCollectionView = new ListCollectionView(Persons);
            PersonsListCollectionView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));

            DataContext = this;
        }

        public ObservableCollection<Person> Persons { get; private set; }
        public ListCollectionView PersonsListCollectionView { get; private set; }
    }

    public class Person
    {
        public string Name { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sev*_*ven 48

最后!如果找到一种更优雅的方式,也可能具有更好的性能.(另请参阅添加时访问ItemsControl项)

我们ItemsControl.AlternateIndex为此"滥用"了财产.最初它旨在以不同的方式处理每一行ListBox.(参见http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.alternationcount.aspx)

1.将AlternatingCount设置为ListBox中包含的项目数

<ListBox ItemsSource="{Binding Path=MyListItems}"
         AlternationCount="{Binding Path=MyListItems.Count}"
         ItemTemplate="{StaticResource MyItemTemplate}"
...
/>
Run Code Online (Sandbox Code Playgroud)

2.绑定到AlternatingIndex您的DataTemplate

<DataTemplate x:Key="MyItemTemplate" ... >
    <StackPanel>
        <Label Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplatedParent.(ItemsControl.AlternationIndex)}" />
        ...
    </StackPanel>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

所以这没有转换器,一个额外的CollectionViewSource,最重要的是没有暴力搜索源集合.

  • 使用虚拟化时,"AlternationIndex"非常无用 (2认同)

Dav*_*own 4

这应该让你开始:

http://weblogs.asp.net/hpreishuber/archive/2008/11/18/rownumber-in-silverlight-datagrid-or-listbox.aspx

它说它适用于Silverlight,但我不明白为什么它不能用于WPF.基本上,您将TextBlock绑定到数据并使用自定义值转换器输出当前项的编号.