从 ListView 访问或更改数据

Access or alter data from ListView

我有一个像这样的简单列表视图

<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>

我可以添加项目、排序或删除它们,例如:

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

但我现在如何访问或更改数据?这没有给我 Coordinate:

的属性
CoordinateList.Items[i].

ListView 将其 Items 集合存储为对象,因此要将项目作为 Coordinate 对象进行访问,您需要先将其转换为 Coordinate 类型。例如:

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

编辑:另请参阅@Muds 的回答以获得更好的练习。

我建议您将 ListView 与一个集合绑定,然后从该集合中添加删除或访问对象。

依赖 UI 代码隐藏的数据操作控件是不可取的。

<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>

然后,

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

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

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