Sometimes we might want to add a sequence number before the ListBox list item, so that it looks clearer and can be used with shortcut keys and so on.
Want to achieve the effect as follows:
Obviously we can do this by modifying the template for the ListBox, as long as you add a number to the item, you can use MultiBinding and imultivalueconverter.
Example
First, we create a person class:
public class person{Public string Name {get; set;}}
Then create a Converter that inherits from the Imultivalueconverter:
Note that line 5th to 6th, which uses the dynamic type, must ensure that the list has IndexOf this extension method,ienumerable<t> is not possible.
public class indexconverter:imultivalueconverter{Public object Convert (object[] values, Type targetType, Object pa Rameter, CultureInfo culture) { Dynamic item = values[0]; Dynamic list = values[1]; Return list. IndexOf (person) + 1; } Public object[] Convertback (object value, type[] targettypes, object parameter, CultureInfo culture) { throw new NotImplementedException (); }}
The XAML is as follows:
The key is to 17~20 rows, each binding the individual data and the ListBox itself.
<window x:class= "Listboxindex.mainwindow" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml" Xmlns:listboxindex = "Clr-namespace:listboxindex" T Itle= "MainWindow" Height = "width=", "525" > <Window.Resources> <listboxindex:indexconverter x:key= "Indexconverter"/> </Window.Resources> <stackpanel > <button name= "Btndemo" content= "Add" C lick= "Btndemo_onclick"/> <listbox name= "Lbxdemo" > <ListBox.ItemTemplate> & Lt;datatemplate datatype= "Listboxindex:person" > <stackpanel orientation= "Horizontal" > <textblock text= "{Binding}" > <TextBlock.DataContext> <multibinding converter= "{StaticResource indexconverter}" > <b Inding/> <binding elementname= "Lbxdemo" path= "ItemsSource"/> </multi Binding> </TextBlock.DataContext> </TextBlock> <textblock text= "{Binding Name}"/> </StackPanel> </datatempl ate> </ListBox.ItemTemplate> </ListBox> </stackpanel ></Window>
The code is as follows:
namespace listboxindex{//<summary>// MainWindow.xaml Interactive logic/// </summary> public Partial class Mainwindow:window { readonly observablecollection <Person> _personlist = new ObservableCollection <Person> (); Public MainWindow () { InitializeComponent (); Initsource (); } private void Initsource () { _personlist.add (new person () {Name = "Liu Bei"}) ; _personlist.add (new person () {Name = "Guan Yu"}); Lbxdemo.itemssource = _personlist; } private void Btndemo_onclick (object sender, RoutedEventArgs e) { _personlist.add (new person () {Name = "Zhang Fei"}); lbxdemo.itemssource = _personlist;}} }
How to add a sequence number to a ListBox list item before WPF