WPF数据网格不允许用户添加空行

本文关键字:添加 用户 不允许 数据 数据网 网格 WPF | 更新日期: 2023-09-27 17:59:26

我已将DataGrid绑定到<ObservableCollection> People。它按预期生成列。我的问题是,我想让用户添加空白行。我该怎么做?

这是我的完整代码:

<Window x:Class="WpfApplication5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <DataGrid AutoGenerateColumns="True" 
                  ItemsSource="{Binding People}" 
                  CanUserAddRows="True"/>
    </StackPanel>
</Window>
public class Person
{
    public Person(string firstName, string lastName)
    {
        Firstname = firstName;
        Lastname = lastName;
    }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}
public sealed class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private ObservableCollection<Person> people = new ObservableCollection<Person>
    {
        new Person("Jack", "Shephard"),
        new Person("John", "Locke")
    };
    public ObservableCollection<Person> People
    {
        get { return people; }
        set
        {
            people = value;
            OnPropertyChanged("People");
        }
    }
    private void OnPropertyChanged(string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        var viewModel = new ViewModel();
        DataContext = viewModel;
    }
}

WPF数据网格不允许用户添加空行

为可观察类添加一个标准构造函数(如果需要区分,可以制作一个类包装器)

public class Person
{
    public Person()
    {