我有一个已排序的列表框,需要显示每个项目的行号。在此演示中,我有一个带有 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; }
}
}
最后!如果找到一种更优雅并且可能具有更好性能的方法。
(也可以看看添加 ItemsControl 项时访问它 https://stackoverflow.com/questions/2007177/accessing-an-itemscontrol-item-as-it-is-added/2007747#2007747)
我们“滥用”财产ItemsControl.AlternateIndex
为了这。最初它的目的是处理一个ListBox
不同。 (看http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.alternationcount.aspx 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}"
...
/>
2. 绑定到您的 DataTemplate 的 AlternatingIndex
<DataTemplate x:Key="MyItemTemplate" ... >
<StackPanel>
<Label Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplatedParent.(ItemsControl.AlternationIndex)}" />
...
</StackPanel>
</DataTemplate>
所以这不需要转换器,额外的CollectionViewSource
最重要的是,无需强力搜索源集合。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)