Like add to ListBox button at the beginning or end of the list?

It is necessary to do so in edit mode at the beginning or end of the list there is a button for adding a new record.
Something like this f1fFy.png

at the moment there is this code
<listbox itemssource="{Binding Items}">
<listbox.itemspanel>
<itemspaneltemplate>
 <uniformgrid> 
</uniformgrid></itemspaneltemplate>
</listbox.itemspanel>
 </listbox>


Trying to add a button programmatically (through the Items.Add(button...)) logical RAID ends with the error - Operation is not valid while ItemsSource is in use
How to be?
June 3rd 19 at 18:57
2 answers
June 3rd 19 at 18:59
Solution
When Beeding collection to the ItemsControl creates a CollectionView (IEnumerable, IList - ListCollectionView) which can optionally sort or filter the collection. The elements visible on the screen, taken from this CollectionView, not from the original collection.

ListCollectionView has a property NewItemPlaceholderPosition, which you can use to add fake element to the beginning or end.
// CollectionView can be obtained in two ways:
// 1. Just get default variant for the collection
var collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(Items);
// 2. To create your own, then that created the collectionView should be transferred to binding in ItemsSource.
var collectionView = new ListCollectionView(Models);

// After, you can add a fake element
collectionView.NewItemPlaceholderPosition = NewItemPlaceholderPosition.AtBeginning;

After that, the ListBox appears CollectionView.NewItemPlaceholder which can be separately styled using the DataTemplateSelector.

DataTemplateSelector
public sealed class NewItemTemplateSelector : DataTemplateSelector
{
 public DataTemplate ItemTemplate { get; set; }
 public DataTemplate NewItemPlaceholderTemplate { get; set; }

 public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
 if (item == CollectionView.NewItemPlaceholder)
 return NewItemPlaceholderTemplate;

 return ItemTemplate;
}
}

<listbox.itemtemplateselector>
<t:newitemtemplateselector>
<t:newitemtemplateselector.itemtemplate>
<datatemplate>
 <!-- The usual pattern element -->
</datatemplate>
</t:newitemtemplateselector.itemtemplate>
<t:newitemtemplateselector.newitemplaceholdertemplate>
<datatemplate>
 <!-- Template CollectionView.NewItemPlaceholder -->
 </datatemplate></t:newitemtemplateselector.newitemplaceholdertemplate></t:newitemtemplateselector></listbox.itemtemplateselector>
June 3rd 19 at 19:01
Use DataTemplateSelector. Well, read about binding collections to controls and other related things.

Find more questions by tags C#WPF