[英]Changing ListBox ItemsSource property while item is selected results in IndexOutOfRange Exception
If I change the ItemsSource
property of a ListBox
while an item is selected I get IndexOutOfRange exception because SelectedIndex
property is set when an item is selected. 如果在选择一个项目时更改ListBox
的ItemsSource
属性,则会出现IndexOutOfRange异常,因为在SelectedIndex
一个项目时会设置SelectedIndex
属性。 If no item is selected in the ListBox
exception is not raised but even if I set the SelectedItem
property to null before changing the ItemsSource
the exception still occurs if an item was selected because SelectedIndex
property still has a value. 如果在ListBox
没有选择任何项目,则不会引发异常,但是即使我在更改ItemsSource
之前将SelectedItem
属性设置为null,如果选择了某个项目,也会发生异常,因为SelectedIndex
属性仍然具有值。
Is there a solution or a workaround for this problem? 是否有解决此问题的方法或解决方法?
Edit: Here is the sample code because this problem only occurs if I apply a Contains
filter in my LINQ to objects expression AND an item is selected in the ListBox... MyList is a List<>
of CLR objects... 编辑:这是示例代码,因为仅当我将LINQ中的Contains
过滤器应用于对象表达式并且在ListBox中选择了一个项目时,才会出现此问题... MyList是CLR对象的List<>
。
lstMyList.ItemsSource = MyList.Where(i => i.TypeId == 1);
That works fine. 很好 This modified LINQ query also works fine (if no item is selected) but if an item is selected I get IndexOutOfRangeException
此修改的LINQ查询也可以正常工作(如果未选择任何项目),但是如果选择了一个项目,则会得到IndexOutOfRangeException
lstMyList.ItemsSource = MyList.Where(i => i.TypeId == 1 && i.DisplayName.Contains(someString));
If I redirect this LINQ query to a var or a list of CLR objects the query works fine but when I try to make it an ItemsSource of my ListBox I get the exception (even if I make this var or a list of CLR object ItemsSource of my ListBox instead). 如果我将此LINQ查询重定向到一个var或CLR对象的列表,该查询可以正常工作,但是当我尝试使其成为ListBox的ItemsSource时,我会收到异常(即使我将此var或一个CLR对象ItemsSource的列表)我的列表框)。
Just set SelectedIndex
to -1 只需将SelectedIndex
设置为-1
EDIT: OK, try that instead: 编辑:确定,请尝试代替:
listBox.ClearValue(Selector.SelectedIndexProperty);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.