我有一个特定类类型 Person 的列表,我想用它制作一个 DataGrid.
I have a list of a specific class type Person and I want to make a DataGrid with it.
private void DataGrid_Loaded(object sender, RoutedEventArgs e) { List<Person> x; //Don't worry, x has data in it (sender as DataGrid).ItemsSource = x; }还有 Person 类:
class Person { string fName, lName; }毕竟我得到了一个带有标题的表格:fName"和lName".如何将其更改为:名字"和姓氏"?
After all this I get a table with the headers: "fName" and "lName". How can I change that to: "First Name" and "Last Name"?
推荐答案正确的做法是:
首先在代码隐藏中定义一个ObservableCollection,用于保存人员列表
First Define an ObservableCollection in the codebehind that will hold a list of persons
第二 将该列表绑定到 DataGrid ItemSource 并绑定其属性
Second Bind that list to the DataGrid ItemSource and Bind its properties
您可以通过简单地禁用 AutoGenerateColumns 并自行设置它们的名称来更改每列显示的名称
You can change what name to display on each column by simply disabling the AutoGenerateColumns and setting their names by your self
这里是完整代码
<DataGrid ItemsSource="{Binding ListPersons}" AutoGenerateColumns="False"> <DataGrid.Columns > <DataGridTextColumn Header="First Name" Binding="{Binding FName}"></DataGridTextColumn> <DataGridTextColumn Header="Last Name" Binding="{Binding LName}"></DataGridTextColumn> </DataGrid.Columns> </DataGrid>和背后的代码:
public class Person { public String FName { get; set; } public String LName { get; set; } } public partial class MainWindow : Window { public ObservableCollection<Person> ListPersons { get; set; } public MainWindow() { ListPersons=new ObservableCollection<Person>() { new Person() { FName = "FName1", LName = "LName1" }, new Person() { FName = "FName2", LName = "LName2" } }; this.DataContext = this; } }更多推荐
更改 DataGrid 列标题文本
发布评论