[英]WPF datagrid does not allow user to add blank rows
I've bound my DataGrid
to <ObservableCollection> People
. 我已经将DataGrid
绑定到<ObservableCollection> People
。 It generates the columns as expected. 它会按预期生成列。 My problem is that I want to let the user add blank rows. 我的问题是我想让用户添加空白行。 How can I do that? 我怎样才能做到这一点?
Here is my complete code: 这是我完整的代码:
<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;
}
}
Add a standard constructor for the observable class (you can make a class wrapper if you need to differentiate it) 为可观察的类添加一个标准的构造函数(如果需要区分,可以制作一个类包装器)
public class Person
{
public Person()
{
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.