c# - 编号列表框

标签 c# wpf listbox

我有一个已排序的列表框,需要显示每个项目的行号。在此演示中,我有一个带有 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/745568/

相关文章:

wpf - 如何使用 wpf 向数据网格的 DataGridTemplateColumn 添加多个控件?

c# - Windows Phone 8,覆盖旧应用程序?

wpf - WPF 中自动剪辑 TextBlock

c# - 查询数据库的数组 int

c# - DataGrid 方法 DataSource 未找到

ms-access - 特殊的列表框。重新查询视觉错误

wpf - 切换按钮组 : Ensuring one item is always selected in a ListBox

vb.net - 从列表框中删除多个项目或行 VB.NET

c# - 调用代码隐藏的确认对话框并获取所选选项

c# - 在 ASP.NET Core 2.1 中设置选定的选项