[英]Row number in wpf datagrid row
我有datagrid綁定ICollectionView列表對象。 基本上,行是根據一列中的值進行過濾的。 現在每行都有一個索引列。 這基本上是行號。 由於行被過濾,行號會發生變化。 怎么辦呢?
基本上DataGrid綁定到類對象的列表。
Class city
{
Int Index;
String Name;
string location;
}
List<city> Cities;
當我創建對象時,索引具有根據索引中項目的數量的值。 因此第一個對象將具有index = 0,第二個將具有index = 1,依此類推。 索引是網格中的一列。 現在讓我說我有2個位置迪拜的物體。 和一個與開羅(第三個對象,索引= 3)。 當我選擇Cairo時,將顯示該行。 但是因為我之前添加了索引,索引號= 3,因為我希望它為1,因為過濾器后面只有一行。
如果要顯示行索引,可以使用AlternationIndex 。 使用AlternationIndex
時,有兩件事很重要:
AlternationCount
。 這就像AlternationIndex
的計數限制之后,如果元素數量超過該計數,它將從0重新開始。 理想情況下,如果您不希望它從0重新啟動,您可以將它綁定到Count Of Items {RelativeSource Mode=TemplatedParent}
{RelativeSource AncestorType=ListBoxItem}
{RelativeSource Mode=TemplatedParent}
試試下面的示例:
<ListBox Name="CityListBox" AlterationCount={Binding CountOfItems}
<ListBox.ItemTemplate>
<DataTemplate DataType="City">
<TextBlock>
<Run Text="{Binding Name}"></Run>
<Run Text=" : "></Run>
<Run Text="{Binding Country}"></Run>
<Run Text=" : "></Run>
<Run Text="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem},
Path=(ItemsControl.AlternationIndex), Mode=OneWay}"></Run>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
產量
CityA : CountryA : 0
CityB : CountryB : 1
CityC : CountryC : 2
通常需要做的是先設置索引的值,然后應用過濾器。
包括System.Linq命名空間並添加以下內容
cities = cities.Select((item, index) =>
new city()
{
Index = index,
Name = item.Name,
location = item.location
});
這將返回第一個索引為零的城市列表。 如果您希望它從一個開始,只需將其更改為:
cities = cities.Select((item, index) =>
new city()
{
Index = index + 1,
Name = item.Name,
location = item.location
});
完成此操作后,您應該應用您的過濾器,除非您要更改值,否則不應覆蓋該過濾器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.