当更改SelectedItem时,Silverlight ListBox抛出超出范围的异常



我有一些Silverlight XAML曾经工作过,但我似乎不知道我做了什么突然使它停止工作,甚至如何改变它。

下面是一些XAML:

<ListBox ItemsSource="{Binding ItemsForSelectedPublisher}"
         SelectedItem="{Binding SelectedItemForPublisher, Mode=TwoWay}"
         DisplayMemberPath="ItemNameWithSelectionCount"
         SelectionMode="Single"
         HorizontalAlignment="Left" 
         FontSize="14" 
         Width="300" 
         Height="500"
         />

和一些来自视图模型的代码:

    public ObservableCollection<ItemViewModel> ItemsForSelectedPublisher
    {
        get { return _itemsForSelectedPublisher; }
        private set
        {
            if (_itemsForSelectedPublisher != value)
            {
                _itemsForSelectedPublisher = value;
                RaisePropertyChanged(() => ItemsForSelectedPublisher);
            }
        }
    }
    public ItemViewModel SelectedItemForPublisher
    {
        get { return _selectedItemForPublisher; }
        set
        {
            if (_selectedItemForPublisher != value)
            {
                _selectedItemForPublisher = value;
                RaisePropertyChanged(() => SelectedItemForPublisher);
            }
        }
    }

在ListBox的SelectedItem被更改(第一次设置)之后,以下异常在Silverlight应用程序中被捕获。UnhandledException处理器。

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
   at System.ThrowHelper.ThrowArgumentOutOfRangeException()
   at System.Collections.Generic.List`1.get_Item(Int32 index)
   at System.Windows.Automation.Peers.SelectorAutomationPeer.RaiseSelectionEvents(SelectionChangedEventArgs e)
   at System.Windows.Controls.Primitives.Selector.InvokeSelectionChanged(List`1 unselectedItems, List`1 selectedItems)
   at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
   at System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem(Int32 oldIndex, Int32 newIndex)
   at System.Windows.Controls.ListBox.MakeSingleSelection(Int32 index)
   at System.Windows.Controls.ListBox.HandleItemSelection(ListBoxItem item, Boolean isMouseSelection)
   at System.Windows.Controls.ListBox.OnListBoxItemClicked(ListBoxItem item)
   at System.Windows.Controls.ListBoxItem.OnMouseLeftButtonDown(MouseButtonEventArgs e)
   at System.Windows.Controls.Control.OnMouseLeftButtonDown(Control ctrl, EventArgs e)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName, UInt32 flags)

据我所知,ListBox正在获得一些不正确的索引,但不知道它是什么或为什么会发生这种情况。有人知道这是怎么回事吗?此时我不知道还能去哪里看

经过大量研究,我发现根本原因是我自己的错(这并不奇怪)。显然,在我自己的代码中的错误是在一个不正确的Equals()覆盖我的一些视图模型。这导致ListBox绑定变得混乱,并抛出超出范围的异常。

最新更新