2

I have this at now:

    <ListBox ItemsSource="{Binding Items}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid/> 
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>

But I need something like this THIS. Unfortunately, when I add the button programmatically

ListBox.Items.Add(button);

It throws an error -

Operation is not valid while ItemsSource is in use

Ahmed Aman
  • 2,373
  • 1
  • 19
  • 33
pig_master
  • 31
  • 6
  • 1
    it is not that simple. You could add a '+' button below the listbox. But if you want to be in the same place as the elements, you will have to use a a DataTemplateSelector on the collection, and have an element that is of a `Add_Item_Type`, that will be matched to that type of control. – Lupu Silviu Jul 23 '18 at 06:12
  • It does not have to be a ListBox. Maybe another control, but its must looks like list of tiles, and bindable with itemssource (MVVM). Any ideas? – pig_master Jul 23 '18 at 06:26
  • take a look at [this Q&A](https://stackoverflow.com/questions/35483458/wpf-add-specific-button-to-itemscontrol-itemspanel) – ASh Jul 23 '18 at 06:41

2 Answers2

1

CompositeCollection is exactly what you need. Here is little XAML sample:

<Window ...>
    <!-- You should define your ItemsSource in resources-->
    <Window.Resources>
        <CollectionViewSource x:Key="Names" Source="{Binding Names}" />
    </Window.Resources>

    <Grid>
        <ListBox>
            <ListBox.ItemsSource>
                <CompositeCollection>
                    <CollectionContainer Collection="{Binding Source={StaticResource Names}}" />

                    <ListBoxItem Foreground="Red">Add new...</ListBoxItem>
                </CompositeCollection>
            </ListBox.ItemsSource>

            <!-- Here you can customize everything you want -->
        </ListBox>
    </Grid>
</Window>
Sam Sch
  • 642
  • 7
  • 15
0

Use like this,

var myButton = new Button()
{
   Height = 25,
   Width = 80
   Content = "+",
   Background = Brushes.Gray
}

UniformGrid.Children.Add(myButton);
DotNetUser
  • 415
  • 3
  • 18