Reputation: 10156
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).
Upvotes: 3
Views: 6053
Reputation: 16277
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" />
Upvotes: 10