0
votes

So, the thing is: I have a ListBox with an ItemsTemplate in it as well as a button allready into the ItemsCollection, witch is the "Add item" button. The idea is to add a new item from the ItemsTemplate insite that listbox by clicking the "Add item" button, with is in another ListBoxItem inside the same listbox I want to add a new item to. I know I could just leave the "Add item" button outside the ListBox, but I really like the idea of the button being at the very bottom of the ListBox, because it's more intuitive, so I have to add a new item from the template, but can´t just bind the ItemsSource property, because it must be empty before using it, and it has the ListBoxItem with the add button allready, which is the the only non-template Item in it, then I have to ensure the button is moved to the bottom of the list.

Been searching for a while and found nothing, can´t figure it out.

1
use the normal process for adding items to a list boxpreciousbetine
Instead of an itemtemplate, define two templates which are for 2 datatypes call these rowVM and buttonVM. rowVM templates into whatever you have now. ButtonVM templates into a button. Bind an observablecollection<object> and add into that numerous rowvm then one buttonvm. Bind the button to a command in the windowViewmodel using relativesource. When you add a RowVM use insert. You could alternatively use a compositecollection with buttonvm in a separate collection.Andy

1 Answers

0
votes

You can use a CompositeCollection as ItemSource for your ListBox, so your "Add item"-Button is always the last item in your ListBox and also not part of your source collection.

    <ListBox>
        <ListBox.Resources>
            <!-- Your Datatemplates -->
        </ListBox.Resources>
        <ListBox.ItemsSource>
            <CompositeCollection>
                <!-- Bind your original ItemsSource here, in my case 'Collection' -->
                <CollectionContainer Collection="{Binding Source={StaticResource mainViewModel}, Path=Collection}"/>
                <!-- Focusable="False" not selectable -->
                <ListBoxItem Focusable="False">
                    <Button Command="{Binding Source={StaticResource mainViewModel}, Path=AddItemCommand}">Add Item</Button>
                </ListBoxItem>
            </CompositeCollection>
        </ListBox.ItemsSource>
    </ListBox>

See also How do you bind a CollectionContainer to a collection in a view model? why you need to specify the Source in bindings