WPF - 多列ListView添加数据的多种方式

时间:2024-10-19 21:34:38

多列ListView:

  WPF - 多列ListView添加数据的多种方式

        <ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="序号" Width=""/>
<GridViewColumn Header="姓名" Width=""/>
<GridViewColumn Header="成绩" Width=""/>
</GridView>
</ListView.View>
</ListView>

多列ListView填充数据:

一、使用DataTable填充

xml代码:

        <ListView x:Name="listView" ItemsSource="{Binding}">
<ListView.View>
<GridView>
<GridViewColumn Header="序号" Width="" DisplayMemberBinding="{Binding Num}"/>
<GridViewColumn Header="姓名" Width="" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="成绩" Width="" DisplayMemberBinding="{Binding Score}"/>
</GridView>
</ListView.View>
</ListView>

cs代码:

using System.Data;

DataTable dt = new DataTable();
dt.Columns.Add("Num");
dt.Columns.Add("Name");
dt.Columns.Add("Score");
dt.Rows.Add(,"章鱼",);
dt.Rows.Add(1,"胖虎",);
dt.Rows.Add(2,"暴君",);
listView.DataContext = dt;

效果:

WPF - 多列ListView添加数据的多种方式

二、使用匿名对象填充

xml代码:

        <ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="序号" Width="" DisplayMemberBinding="{Binding Num}"/>
<GridViewColumn Header="姓名" Width="" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="成绩" Width="" DisplayMemberBinding="{Binding Score}"/>
</GridView>
</ListView.View>
</ListView>

cs代码:

            listView.Items.Add(new { Num = "", Name = "A", Score = ""});
listView.Items.Add(new { Num = "", Name = "B", Score = "" });
listView.Items.Add(new { Num = "", Name = "C", Score = "" });

效果:

WPF - 多列ListView添加数据的多种方式

三、使用实例对象(推荐)

xml代码:

        <ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="序号" Width="" DisplayMemberBinding="{Binding Num}"/>
<GridViewColumn Header="姓名" Width="" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="成绩" Width="" DisplayMemberBinding="{Binding Score}"/>
</GridView>
</ListView.View>
</ListView>

cs代码:

        public MainWindow()
{
InitializeComponent(); listView.Items.Add(new StudentInfo(, "小花", ));
listView.Items.Add(new StudentInfo(, "小草", ));
listView.Items.Add(new StudentInfo(, "小蚂蚁", ));
} class StudentInfo
{
public int Num { set; get; }
public string Name { set; get; }
public int Score { set; get; } public StudentInfo(int num,string name,int score)
{
this.Num = num;
this.Name = name;
this.Score = score;
}
}

效果:

WPF - 多列ListView添加数据的多种方式