Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法强制转换类型为';System.String';到;。。控件。SurfaceListBoxItem';例外_C#_Wpf_Pixelsense - Fatal编程技术网

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();