WPF DataGrid控件有多种方式可以添加数据。以下是其中的几种常用方法:
直接在XAML中定义静态数据:您可以在XAML中定义DataGrid的静态数据,使用<DataGrid.Items>元素,并在其内部使用<DataGrid> <DataGrid.Columns> <DataGridTextColumn Header="Name" Binding="{Binding Name}" /> <DataGridTextColumn Header="Age" Binding="{Binding Age}" /> </DataGrid.Columns> <DataGrid.Items> <Person Name="John" Age="30" /> <Person Name="Alice" Age="25" /> </DataGrid.Items></DataGrid>使用ItemsSource属性绑定动态数据集合:您可以在代码中创建一个数据集合,并将其绑定到DataGrid的ItemsSource属性。例如:public class Person{ public string Name { get; set; } public int Age { get; set; }}// 在代码中创建数据集合List<Person> people = new List<Person>();people.Add(new Person { Name = "John", Age = 30 });people.Add(new Person { Name = "Alice", Age = 25 });// 将数据集合绑定到DataGrid的ItemsSource属性myDataGrid.ItemsSource = people;使用DataTable或DataView绑定动态数据:您可以使用DataTable或DataView对象创建和管理数据,然后将其绑定到DataGrid的ItemsSource属性。例如:// 创建DataTable对象DataTable dataTable = new DataTable("People");dataTable.Columns.Add("Name", typeof(string));dataTable.Columns.Add("Age", typeof(int));// 添加行数据dataTable.Rows.Add("John", 30);dataTable.Rows.Add("Alice", 25);// 将DataTable绑定到DataGrid的ItemsSource属性myDataGrid.ItemsSource = dataTable.DefaultView;以上是几种常用的添加数据的方法,您可以根据需求选择适合的方法来添加数据到WPF DataGrid控件中。