Search code examples
wpfdata-bindingitemscontrolselectedindex

WPF - Binding to an ItemsSource AND SelectedIndex throws exception?


This code gives me an “Argument out of range” exception. When I remove the binding to the SelectedIndex, the ComboBox is populated just fine and no exception is thrown.

Any idea what I am doing wrong? Is this (for some reason) not possible?

Code:

public class RuleMap<T> : INotifyPropertyChanged
{
    public ObservableCollection<string> Options
    {
        get
        {
            return new ObservableCollection(){"A", "B", "C"};
        }
    }

    public int SelectedIndex
    {
        get
        {
            return 0;
        }
    }
}

public ObservableCollection<RuleMap> FilterItemSource;

XAML:

<ItemsControl ItemsSource="{Binding FilterItemSource}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">                                 <ComboBox Width="150" SelectedIndex="{Binding SelectedIndex}"
                          ItemsSource="{Binding Options}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Solution

  • Turns out the ComboBox control was fundamentally broken to begin with. Thanks to this Blog Post by Rockford Lhotka, we were able to override the ComboBox control with one that could correctly bind to SelectedItem property.

    Ick.