2

I want to implement an ItemsControl with a button that adds the same content with another ViewModel. So far I have this code:

<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Controls:ItemView />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The button should always be the last item in the control and it should have only one add button. Does anyone have a good solution? I could do it on my own with ugly workarounds but I hate ugly workarounds :)

Hans Dabi
  • 159
  • 13
  • So you want a button that will add an element to `Items` ? – Andy Mar 31 '16 at 08:35
  • Basically yes, but my main problem is that I don't know how to add a button to the Itemscontrol that is always on the bottom and exists just one time. – Hans Dabi Mar 31 '16 at 08:59
  • Perhaps you need to use a compositecollection ? See http://stackoverflow.com/questions/6446699/how-do-you-bind-a-collectioncontainer-to-a-collection-in-a-view-model – auburg Mar 31 '16 at 09:40
  • Why not just leave the button outside of the ItemsControl ? When you click on the `button`, you add the element to `Items` and it will be displyed by the `ItemsControl`. – Andy Mar 31 '16 at 10:53

1 Answers1

8

You need to customize the Template of your ItemsControl in order to add the Button below the ItemsPresenter:

<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Controls:ItemView />
        </DataTemplate>
    </ItemsControl.ItemTemplate>

    <ItemsControl.Template>
        <ControlTemplate TargetType="ItemsControl">
            <StackPanel>
                <ItemsPresenter />
                <Button Content="Add Item"  Click="AddItem_Click"/>
            </StackPanel>
        </ControlTemplate>
    </ItemsControl.Template>

</ItemsControl>
Andy
  • 3,631
  • 2
  • 23
  • 32