我一直想知道在WPF中是否可以创建一个ListView
,其行号不会绑定到IEnumerable<>
的索引属性?也许制作一个自动增加行号的模板?如何实现?
在某些情况下(例如,当您使用以令人不快的形式返回大量数据的外部类时 - 例如字典或某些自定义类),它可能很有用。
答案 0 :(得分:10)
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" />