我要做的就是将列表框中的每个值与选定的值进行比较,然后将匹配索引设置为选定的。出于某种原因,引发了标题中的异常。我不明白为什么。代码:
foreach(SurfaceListBoxItem n in BackgroundsList.Items)
{
if (n.ToString() == current) BackgroundsList.SelectedItem = n;
}
谢谢!
我要做的就是将列表框中的每个值与选定的值进行比较,然后将匹配索引设置为选定的。出于某种原因,引发了标题中的异常。我不明白为什么。代码:
foreach(SurfaceListBoxItem n in BackgroundsList.Items)
{
if (n.ToString() == current) BackgroundsList.SelectedItem = n;
}
谢谢!
在 WPF 中,List.Items 不一定包含 ListBoxItem 的集合,它只包含数据值,并且数据的 Item Container 是派生的,要设置值,您必须简单地将 current 设置为选定项。
无需迭代,您可以简单地执行以下操作,
BackgroundsList.SelectedItem = current;
C# foreach 语句为您执行从返回的元素类型Items
到指定SurfaceListBoxItem
类型的隐式转换。在运行时返回的string
不能被强制转换为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();