Reputation: 5656
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>
Upvotes: 1
Views: 1493
Reputation: 5656
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.
Upvotes: 1
Reputation: 69262
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.
Upvotes: 0
Reputation: 17669
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.
Upvotes: 1
Reputation: 39413
I guess that SelectedIndex
it is a ReadOnly Property.
Other problem can be that 0 it's not in the collection
Upvotes: 1