Reputation: 807
I have datagrid bound a ICollectionView list object. Basically the rows are filtered based on a value in one column. Now there is a index column in each of the row. This is basically the row number . Since the rows are filtered the row number changes. How to handle this ?
Basically DataGrid is bound to a list of class object.
Class city
{
Int Index;
String Name;
string location;
}
List<city> Cities;
When i create the object, index has the value according to the no of items in the index. So the first object will have index =0, second will have index=1 and so on. Index is a column in the grid. Now lets say i have 2 objects with location Dubai. and one with Cairo(3rd object , with Index=3). When i select Cairo Only that row will be displayed. But since i have added the index earlier , index number=3 where as i want it to be 1 since there is only one row after the filter.
Upvotes: 0
Views: 2392
Reputation: 7903
You can Use AlternationIndex when you want to show Row Index. Two things are important when you are using AlternationIndex
:
AlternationCount
for the control. This is like a counting limit for AlternationIndex
after that it will restart from 0 if your number of elements exceeds that count. Ideally you can bind it to Count Of Items if you dont want it to restart from 0{RelativeSource AncestorType=ListBoxItem}
for others it can be {RelativeSource Mode=TemplatedParent}
Try this Sample below:
<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>
Output
CityA : CountryA : 0
CityB : CountryB : 1
CityC : CountryC : 2
Upvotes: 2
Reputation: 438
what will typically need to do is to set the value for index first, then apply the filter.
include the System.Linq namespace and add the following
cities = cities.Select((item, index) =>
new city()
{
Index = index,
Name = item.Name,
location = item.location
});
This will bring back a list of cities where the first index would be zero. If you want it to start from one simply change it to :
cities = cities.Select((item, index) =>
new city()
{
Index = index + 1,
Name = item.Name,
location = item.location
});
After this has been completed you should apply your filter, which shouldn't be overridden unless you are changing the values.
Upvotes: 0