3
我一直想知道WPF中是否有可能創建一個ListView
,它有行號而不綁定到IEnumerable<>
的索引屬性?也許製作一個自動增量行號的模板?如何實現這一點?ListView沒有綁定的行號
在某些情況下它可能很有用(例如,當您使用一個外部類以不愉快的形式返回大量數據時 - 如字典或某個自定義類)。
我一直想知道WPF中是否有可能創建一個ListView
,它有行號而不綁定到IEnumerable<>
的索引屬性?也許製作一個自動增量行號的模板?如何實現這一點?ListView沒有綁定的行號
在某些情況下它可能很有用(例如,當您使用一個外部類以不愉快的形式返回大量數據時 - 如字典或某個自定義類)。
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" />
你是一個genious和紳士!謝謝:) – Nickon
* [...]無綁定到IEnu merable <>的索引屬性[...] *這種方法有什麼問題?雖然我不確定你想如何綁定到這個屬性... – DHN
正如我所描述的。當你得到數據時作爲字典(並且有大量字典),將它們更改爲列表或表格(或包含索引的東西)代價非常高:/ – Nickon
您可以使用替代計數。檢查我的答案在另一個問題:http://stackoverflow.com/questions/15282801/display-row-numbers-in-wpf-listview/15283680#15283680 –