WPF: Two DataGrids, same ItemsSource, One IsReadOnly, Bug?

耗尽温柔 提交于 2019-11-30 16:23:32
Fredrik Hedblad

I think what's going on is that the IsReadOnly property is making the DataGrid readonly through the DefaultView for persons, and since this DefaultView will be the same for both of your DataGrid's, both looses the ability to add new rows.

Both doesn't become readonly however (as you said in your question) so I'm not sure if this is a bug or a desired behavior.

I'm also not sure what's going on behind the scenes here that causes this behavior but you can verify that the CollectionView's are the same through the debugger (since the CollectionView property is private). The following three statements come out as true

dgA.Items.CollectionView == CollectionViewSource.GetDefaultView(persons) // true
dgB.Items.CollectionView == CollectionViewSource.GetDefaultView(persons) // true
dgA.Items.CollectionView == dgB.Items.CollectionView // true

You can get it to work the way you like by changing the List to an ObservableCollection and use separate ListViewCollection's for your DataGrid's

public MainWindow()
{
    InitializeComponent();

    ObservableCollection<Person> persons = new ObservableCollection<Person>();
    persons.Add(new Person() { FirstName = "Bob", LastName = "Johnson" });
    persons.Add(new Person() { FirstName = "John", LastName = "Smith" });

    dgA.ItemsSource = new ListCollectionView(persons);
    dgB.ItemsSource = new ListCollectionView(persons);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!