从ListView访问或更改数据

时间:2015-10-20 08:17:06

标签: c# wpf listview itemcollection

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

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

2 个答案:

答案 0 :(得分:0)

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

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

编辑:另见@ Muds&#39;回答更好的做法。

答案 1 :(得分:0)

我建议你将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.