无法转换“System.String”类型的对象到“..Controls.SurfaceListBoxItem”例外
我想做的就是将列表框中的每个值与选定的值进行比较,然后将匹配索引设置为选定的。 由于某种原因,标题中出现了例外情况。我不明白为什么。 代码:
foreach(SurfaceListBoxItem n in BackgroundsList.Items)
{
if (n.ToString() == current) BackgroundsList.SelectedItem = n;
}
谢谢!
All that i'm trying to do is to compare, for each value in a listbox, its value with a chosen one and then set the match index as selected.
For some reason the exception in the title is raised. I don't understand why though.
Code:
foreach(SurfaceListBoxItem n in BackgroundsList.Items)
{
if (n.ToString() == current) BackgroundsList.SelectedItem = n;
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在WPF中,List.Items不一定包含ListBoxItem的集合,而是只包含数据值,并且数据的Item Container是派生的,要设置值,只需将current设置为所选项目即可。
无需迭代,只需执行以下操作即可:
In WPF, List.Items does not necessarily contain collection of ListBoxItem, instead it only contains data values, and the Item Container of the data is derived, to set value, you must simply set current to selected item.
There is no need to iterate, you can simply do following,
C# foreach 语句会执行从
Items
返回的元素类型到指定的SurfaceListBoxItem
类型的隐式转换。在运行时,返回的字符串
无法转换为SurfaceListBoxItem
。您可以使用var
而不是SurfaceListBoxItem
来解决这个问题,或者,当然,您可以使用 LINQ:
The C# foreach statement does an implicit cast for you from the type of the element returned by
Items
to the specifiedSurfaceListBoxItem
type. At runtime the returnedstring
can not be casted toSurfaceListBoxItem
. You can solve this by usingvar
instead ofSurfaceListBoxItem
Or, of course, you can use LINQ: