我有一个特定类类型为 Person 的列表,我想用它创建一个 DataGrid 。 / p>
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:
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列标题文本
发布评论