我有一个已排序的列表框,需要显示每个项目的行号。在此演示中,我有一个带有 Name 字符串属性的 Person 类。列表框显示按姓名排序的人员列表。如何将行号添加到列表框的数据模板???
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>
代码隐藏:
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; }
}
}
最佳答案
终于!如果找到一种更优雅并且可能具有更好性能的方法。 (另见 Accessing an ItemsControl item as it is added)
为此,我们“滥用”了属性 ItemsControl.AlternateIndex
。最初它旨在以不同方式处理 ListBox
中的每一行。 (参见 http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.alternationcount.aspx)
<强>1。将 AlternatingCount 设置为列表框中包含的项目数量
<ListBox ItemsSource="{Binding Path=MyListItems}"
AlternationCount="{Binding Path=MyListItems.Count}"
ItemTemplate="{StaticResource MyItemTemplate}"
...
/>
<强>2。将您的 DataTemplate 绑定(bind)到 AlternatingIndex
<DataTemplate x:Key="MyItemTemplate" ... >
<StackPanel>
<Label Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplatedParent.(ItemsControl.AlternationIndex)}" />
...
</StackPanel>
</DataTemplate>
因此这无需转换器、额外的 CollectionViewSource
并且最重要的是无需暴力搜索源集合即可工作。
关于c# - 编号列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2647291/