Access or alter data from ListView

44 Views Asked by At

i have a simple listview like that

<ListView Name="CoordinateList" Margin="2"
                  Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Nr}"  Header="Nr." Width="40"/>
            <GridViewColumn DisplayMemberBinding="{Binding X}" Header="X" Width="100"/>
            <GridViewColumn DisplayMemberBinding="{Binding Y}" Header="Y" Width="100"/>
            <GridViewColumn DisplayMemberBinding="{Binding Q}" Header="Q" Width="40"/>
        </GridView>
    </ListView.View>
</ListView>

i can add items, sort or remove them e.g.:

CoordinateList.Items.Add(new Coordinate() { Nr = 1, X = 230, Y = 530, Q = 2 });

but how can i access or alter the data now? this doesn't give me the properties of Coordinate:

CoordinateList.Items[i].
2

There are 2 best solutions below

0
DanL On BEST ANSWER

A ListView stores its Items collection as objects, so in order to access an item as a Coordinate object, you need to cast it to a Coordinate type first. E.g.:

var coord = (Coordinate) CoordinateList.Items[i];
...

Edit: Also see @Muds' answer for better practice.

0
Muds On

I would suggest you to bind you ListView with a collection, and then add remove or access objects from that collection.

Relying on UI Controls for data manipulation from code behind is not advisable.

<ListView Name="CoordinateList" ItemsSource="{Binding MyNewList}" Margin="2"
                  Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Nr}"  Header="Nr." Width="40"/>
            <GridViewColumn DisplayMemberBinding="{Binding X}" Header="X" Width="100"/>
            <GridViewColumn DisplayMemberBinding="{Binding Y}" Header="Y" Width="100"/>
            <GridViewColumn DisplayMemberBinding="{Binding Q}" Header="Q" Width="40"/>
        </GridView>
    </ListView.View>
</ListView>

Then,

public ObservableCollection<Coordinate> MyNewList { get; set;}

MyNewList.Add(new Coordinate() { Nr = 1, X = 230, Y = 530, Q = 2 })

MyNewList[I] --> will have your item.