我一直想知道是否有可能在 WPF 中创建一个ListView
具有行号而不绑定到IEnumerable<>
index 属性的?也许制作一个自动增加行号的模板?如何意识到这一点?
在某些情况下它可能很有用(例如,当您使用一个以不愉快的形式返回大量数据的外部类时 - 例如字典或某些自定义类)。
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>
创建一个转换器类:
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();
}
}
在窗口或控件的资源部分:
<Converter:IndexConverter x:Key="IndexConverter" />