如何以编程方式更新Listview(wpf)中特定行中的特定列

时间:2017-03-25 12:14:15

标签: c# wpf listview

我有一个列表视图表see the picture in the link

我想要做的是以编程方式更改第y行中的列x。 我正在使用wpf和listview以及以下xaml代码。

`<ListView x:Name="listView1" Height="153" Width="444">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header ="Code" Width="148"></GridViewColumn>
                        <GridViewColumn Header ="Name" Width="148"></GridViewColumn>
                        <GridViewColumn Header ="Country" Width="148"></GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>

` 我想要做的是以编程方式更改第y行中的列x。 像这样的东西 listview.Items [x] .ColumnIndex [y] =&#34;我的值&#34 ;; 我需要传递一个字符串值,我没有在那里使用数据绑定。

1 个答案:

答案 0 :(得分:0)

图片与您的XAML标记不太匹配。我强烈建议阅读ListViews如何在这里工作的解释:http://www.wpf-tutorial.com/listview-control/simple-listview/

当更改ListView中显示的内容时,会修改ItemsSource及其内容,而不是视觉&#34;单元格&#34;。最好通过数据绑定来完成。

让我们说你的ListView设置如下:

XAML:

<ListView x:Name="myListView">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Code}" Header="Code"/>
            <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name"/>
            <GridViewColumn DisplayMemberBinding="{Binding Country}" Header="Country"/>
        </GridView>
    </ListView.View>
</ListView>

C#:

public class MyInfo
{
    public string Code { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        ...

        ObservableCollection<MyInfo> items = new ObservableCollection<MyInfo>();
        items.Add(new MyInfo() { Code = "mycode1", Name = "myname1", Country = "mycountry1" });
        items.Add(new MyInfo() { Code = "mycode2", Name = "myname2", Country = "mycountry2" });
        items.Add(new MyInfo() { Code = "mycode3", Name = "myname3", Country = "mycountry3" });

        myListView.ItemsSource = items;
    }
}


要更改第二列中的Name值,您可以使用:

items[1].Name = "mynewname2";
相关问题