WPF - 绑定到ItemsSource AND SelectedIndex抛出异常?

时间:2009-12-03 16:09:56

标签: wpf data-binding itemscontrol selectedindex

此代码为我提供了“参数超出范围”异常。当我删除SelectedIndex的绑定时,ComboBox就会很好地填充,并且不会抛出任何异常。

知道我做错了什么吗?这(由于某种原因)不可能吗?

代码:

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>

4 个答案:

答案 0 :(得分:1)

我猜SelectedIndex它是一个ReadOnly属性 其他问题可能是0它不在集合中

答案 1 :(得分:1)

我认为在selectedIndex为Binded之前不会添加Items,并且因为没有item,所以它显示Argument超出Range范围。

答案 2 :(得分:1)

原来,ComboBox控件从根本上被打破了。感谢Rockford Lhotka的Blog Post,我们能够使用可以正确绑定到SelectedItem属性的控件来覆盖ComboBox控件。

伊克。

答案 3 :(得分:0)

我会避免从您的选项属性中返回集合。您假设WPF只访问该属性一次。

但您也可以选择使用CollectionView,当前正在返回ObservableCollection。如果您使用的是MVVM体系结构,则ViewModel可以将该属性公开为CollectionView,并且它具有“当前”项目的概念。

相关问题