温馨提示×

wpf datagrid怎么添加数据

wpf
小亿
192
2023-10-14 03:59:31
栏目: 编程语言

要将数据添加到WPF DataGrid,需要以下步骤:

  1. 创建一个数据源:可以是一个类或一个集合,该类或集合包含将在DataGrid中显示的数据。

  2. 创建DataGrid并设置其ItemsSource属性为数据源。

  3. 在数据源中添加数据。

下面是一个简单的示例,演示如何添加数据到DataGrid:

XAML代码:

<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<Grid>
<DataGrid x:Name="dataGrid" AutoGenerateColumns="True" />
</Grid>
</Window>

C#代码:

using System.Collections.ObjectModel;
using System.Windows;
namespace WpfApp
{
public partial class MainWindow : Window
{
public ObservableCollection<Person> People { get; set; }
public MainWindow()
{
InitializeComponent();
People = new ObservableCollection<Person>();
dataGrid.ItemsSource = People;
// 添加数据
People.Add(new Person("John", "Doe"));
People.Add(new Person("Jane", "Smith"));
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
}

在上述示例中,我们创建了一个名为Person的简单类,该类具有FirstName和LastName属性。然后,我们在MainWindow的构造函数中创建了一个ObservableCollection作为数据源,并将其赋给DataGrid的ItemsSource属性。最后,我们通过调用People集合的Add方法向数据源中添加了一些Person对象。这些Person对象将自动显示在DataGrid中的相应列中。

0