C# WPF datagrid不允许用户添加空行
我已将我的C# WPF datagrid不允许用户添加空行,c#,wpf,mvvm,datagrid,C#,Wpf,Mvvm,Datagrid,我已将我的数据网格绑定到人员。它按预期生成列。我的问题是我想让用户添加空行。我该怎么做 这是我的完整代码: <Window x:Class="WpfApplication5.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Tit
数据网格
绑定到人员
。它按预期生成列。我的问题是我想让用户添加空行。我该怎么做
这是我的完整代码:
<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;
}
}
公共阶层人士
{
公众人物(字符串名、字符串名)
{
名字=名字;
Lastname=Lastname;
}
公共字符串名{get;set;}
公共字符串Lastname{get;set;}
}
公共密封类视图模型:INotifyPropertyChanged
{
公共事件属性更改事件处理程序属性更改;
私人可观察收集人员=新可观察收集
{
新人(“杰克”、“谢泼德”),
新人(“约翰”、“洛克”)
};
公众观察收集人
{
获取{返回人;}
设置
{
人=价值;
不动产变更(“人员”);
}
}
私有void OnPropertyChanged(字符串propertyName=null)
{
var handler=PropertyChanged;
if(handler!=null)handler(这是新的PropertyChangedEventArgs(propertyName));
}
}
公共部分类主窗口:窗口
{
公共主窗口()
{
初始化组件();
var viewModel=新的viewModel();
DataContext=viewModel;
}
}
为可观察类添加标准构造函数(如果需要区分,可以制作类包装器)
为可观察类添加一个标准构造函数(如果需要区分,可以创建一个类包装器)
若设置为true(默认值),则用户应该已经能够添加新行,但它需要无参数构造函数。或者将空的
Person
添加到ObservableCollection
如果设置为true(默认值),则用户应该能够添加新行,但它需要无参数构造函数。或者将空的Person
添加到observedcollection
感谢机器学习,这是解决方案!感谢机器学习,这是解决方案!
public class Person
{
public Person()
{