3

I have always wondered if it's possible in WPF to create a ListView that has row numbers without binding to the IEnumerable<>'s index property? Maybe making a template that autoincrements a row number? How to realise that?

It could be useful in some cases (e.g. when you use an external class that returns tons of data in unpleasant form - like a dictionary or some custom class).

Nickon
  • 9,652
  • 12
  • 64
  • 119
  • *[...] without binding to the IEnumerable<>'s index property[...]* What's wrong with that approach? Although I'm not sure how you want to bind to this property... – DHN Apr 17 '13 at 13:17
  • As I described. When you get the data e.g. as a dictionary (and there are tons of them), changing them to a list or table (or something that contains an index) is very costly:/ – Nickon Apr 17 '13 at 13:20
  • You can use alternation count. Check my answer on another question: http://stackoverflow.com/questions/15282801/display-row-numbers-in-wpf-listview/15283680#15283680 – torrential coding Apr 17 '13 at 13:25
  • Hmm ok, I see. I don't think, that's possible, but perhaps somebody will have an idea. – DHN Apr 17 '13 at 13:31

1 Answers1

10

enter image description here

XAML:

  <ListView.View>
     <GridView>
        <!-- This is the column where the row index is to be shown -->
        <GridViewColumn Width="100" Header="No."
        DisplayMemberBinding="{Binding RelativeSource=
             {RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, 
              Converter={StaticResource IndexConverter}}" />
        <!-- other columns, may be bound to your viewmodel instance -->
        <GridViewColumn Width="100"
        ...
        </GridViewColumn>
    </GridView>
  </ListView.View>

Create a converter class:

public class IndexConverter : IValueConverter
{
    public object Convert(object value, Type TargetType, object parameter, CultureInfo culture)
    {
        var item = (ListViewItem) value;
        var listView = ItemsControl.ItemsControlFromItemContainer(item) as ListView;
        int index = listView.ItemContainerGenerator.IndexFromContainer(item) + 1;
        return index.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

In window or control's resource section:

<Converter:IndexConverter x:Key="IndexConverter" />
David
  • 15,894
  • 22
  • 55
  • 66