C# 无法强制转换类型为';System.String';到;。。控件。SurfaceListBoxItem';例外
我所要做的就是比较列表框中每个值的值与所选值,然后将匹配索引设置为所选。 出于某种原因,提出了标题中的例外情况。我不明白为什么。 代码:C# 无法强制转换类型为';System.String';到;。。控件。SurfaceListBoxItem';例外,c#,wpf,pixelsense,C#,Wpf,Pixelsense,我所要做的就是比较列表框中每个值的值与所选值,然后将匹配索引设置为所选。 出于某种原因,提出了标题中的例外情况。我不明白为什么。 代码: 谢谢 在WPF中,List.Items不一定包含ListBoxItem的集合,相反,它只包含数据值,并且数据的项容器是派生的。要设置值,只需将current设置为selected Item即可 不需要迭代,您只需执行以下操作 BackgroundsList.SelectedItem = current; C#foreach语句为您执行隐式转换,从Items返
谢谢 在WPF中,List.Items不一定包含ListBoxItem的集合,相反,它只包含数据值,并且数据的项容器是派生的。要设置值,只需将current设置为selected Item即可 不需要迭代,您只需执行以下操作
BackgroundsList.SelectedItem = current;
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();
BackgroundsList.SelectedItem = (
from n in BackgroundList.Items
where n.ToString() == current
select n).FirstOrDefault();