0
votes

I would need to have a ItemsControl with buttons for displaying the ItemSources. And I would need a comboBox to add items to the buttons to the ItemsSource. You choose an item from the comboBox and it gets added to the ItemsControl ItemsSource list. For example, I have a list of persons in the comboBox, I click one person on the comboBox and it is added to the ItemsContol Persons Binding. How can I achieve this ?

<ItemsControl ItemsSource="{Binding Persons}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding FullName}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ComboBox ItemsSource="{Binding}"></ComboBox>
</ItemsControl>

The items control need to have Buttons for the persons and a comboBox to add persons from

The items control with the persons

1

1 Answers

0
votes

Bind the SelectedItem property of the ComboBox to a source property and then add an item to Persons collections in the setter of this one:

public List<Person> PersonToSelectFrom{ get; } = new List<Person>();

public ObservableCollection<Person> Persons { get; } = new ObservableCollection<Person>();

private Person _selectedPerson;
public Person SelectedPerson
{
    get { return _selectedPerson; }
    set
    {
        _selectedPerson = value;
        if (_selectedPerson != null && !Persons.Contains(_selectedPerson))
            Persons.Add(_selectedPerson);
    }
}

XAML:

<ComboBox ItemsSource="{Binding PersonToSelectFrom}"
          SelectedItem="{Binding SelectedPerson}" ... />

Note that the collection bound to the ItemsControl must implement the INotifyCollectionChanged interface for the view to ge refreshed when you add an item to the source collection. The ObservableCollection<T> class does this but List<T> doesn't.