C#C
C#14mo ago
1 reply
Tiranozavr

WPF: Binding selected item of ComboBox inside ItemsControl

Hello, I'm currently exploring WPF and kinda stuck with one particular case.

I have ItemsControl with ItemTemplate being a ComboBox:
<ItemsControl ItemsSource="{Binding Values}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <ComboBox Width="150"
                          ItemsSource="{Binding DataContext.Items, RelativeSource={RelativeSource AncestorType=Window}}"
                          SelectedItem="{Binding .}">
                </ComboBox>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Values is a collection in my view model: public ObservableCollection<ComboBoxItemModel> Values { get; set; };
ItemsSource for comboboxes is a fixed List<ComboBoxItemModel>

I can add and remove items and this changes will be reflected in my view: comboboxes will be added and removed. But if I change selected item in a combobox, this won't do anything with the collection.

I've figured out I can create a wrapper class:
public class Wrapper
{
    public ComboBoxItemModel Model {get; set; }
}

And change Values to be a collection of type Wrapper and update my binding to be:
SelectedItem="{Binding Model}"

This way changing selected item of any combobox will update Model field of corresponding Wrapper object in my collection. So far so good, but it seems kinda hacky. Am I doing it right? Is the Wrapper class mandatory in this case?
Was this page helpful?