devarc
devarc

Reputation: 1157

ListCollectionView & DataGrid add row

I use EF and WPF to create application that shows me customer data and allow me to edit this data. Datagrid show me phone numbers on the customer.

Yesterday I've changed my collections from CollectionViewSource to ListCollectionView because I wanted to filter them and sort.

    ((ISupportInitialize)mycollection).BeginInit();
    mycollection.CollectionViewType = typeof(ListCollectionView);
    ((ISupportInitialize)mycollection).EndInit();

But today I realized that there is no additional row for adding new objects if customer doesn't have at least one phone number. Here are some screens for better view:

when tel exists

when tel doesn't exists

In both cases IsEnable and IsReadOnly does not change. Any ideas?

Upvotes: 1

Views: 1370

Answers (1)

helcoder
helcoder

Reputation: 82

When collection is empty, ListCollectionView doesn't know what type of object it needs to add. There's a solution to set type through reflection:

public static void SetTypeToListCollectionView(Type t, CollectionViewSource collectionViewSource)
{
    ListCollectionView repositoryView = (ListCollectionView)collectionViewSource.View;

    if (!repositoryView.CanAddNew)
    {
        ConstructorInfo ci = t.GetConstructor(new Type[] { });
        FieldInfo field = repositoryView.GetType().GetField("_itemConstructor", BindingFlags.Instance | BindingFlags.NonPublic);
        field.SetValue(repositoryView, ci);
    }
}

It's working, but you need to do this before binding CollectionViewSource to DataGrid.ItemsSource

I've did something like this, after setting type:

 BindingOperations.ClearAllBindings(dataGrid);
 BindingOperations.SetBinding(dataGrid, DataGrid.ItemsSourceProperty, new Binding() { Source = collectionViewSource });

Upvotes: 3

Related Questions