无法转换“System.String”类型的对象到“..Controls.SurfaceListBoxItem”例外

发布于 2024-09-11 02:53:26 字数 279 浏览 6 评论 0原文

我想做的就是将列表框中的每个值与选定的值进行比较,然后将匹配索引设置为选定的。 由于某种原因,标题中出现了例外情况。我不明白为什么。 代码:

            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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

﹉夏雨初晴づ 2024-09-18 02:53:26

在WPF中,List.Items不一定包含ListBoxItem的集合,而是只包含数据值,并且数据的Item Container是派生的,要设置值,只需将current设置为所选项目即可。

无需迭代,只需执行以下操作即可:

BackgroundsList.SelectedItem = 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,

BackgroundsList.SelectedItem = current;
写给空气的情书 2024-09-18 02:53:26

C# foreach 语句会执行从 Items 返回的元素类型到指定的 SurfaceListBoxItem 类型的隐式转换。在运行时,返回的字符串无法转换为SurfaceListBoxItem。您可以使用 var 而不是 SurfaceListBoxItem 来解决这个问题,

foreach(var n in BackgroundsList.Items)
{
    if (n.ToString() == current) BackgroundsList.SelectedItem = n;
}

或者,当然,您可以使用 LINQ:

BackgroundsList.SelectedItem = (
    from n in BackgroundList.Items
    where n.ToString() == current
    select n).FirstOrDefault();

The C# foreach statement does an implicit cast for you from the type of the element returned by Items to the specified SurfaceListBoxItem type. At runtime the returned string can not be casted to SurfaceListBoxItem. You can solve this by using var instead of SurfaceListBoxItem

foreach(var n in BackgroundsList.Items)
{
    if (n.ToString() == current) BackgroundsList.SelectedItem = n;
}

Or, of course, you can use LINQ:

BackgroundsList.SelectedItem = (
    from n in BackgroundList.Items
    where n.ToString() == current
    select n).FirstOrDefault();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文