我已将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;
}
}
答案 0 :(得分:2)
为可观察类添加标准构造函数(如果需要区分它,可以创建类包装器)
df