Question

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>
Was it helpful?

Solution 3

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.

OTHER TIPS

I guess that SelectedIndex it is a ReadOnly Property.
Other problem can be that 0 it's not in the collection

I think that Items are not added before selectedIndex is Binded, and since there are no item, it is showing Argument out of Range exception.

I would avoid returning a new collection from your Options property. You're making an assumption that WPF only accesses the property once.

But you also have the option of using a CollectionView where you're currently returning an ObservableCollection. If you're using a MVVM architecture, your ViewModel can expose the property as CollectionView and it has the notion of a "current" item.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top