Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListView row numbers without binding

Tags:

c#

wpf

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).

like image 269
Nickon Avatar asked Apr 25 '26 10:04

Nickon


1 Answers

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" />
like image 53
David Avatar answered Apr 27 '26 23:04

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!