2010-07-22 121 views

回答

2

在WPF,List.Items做不一定包含ListBoxItem的集合,相反它只包含数据值,并且导出数据的Item Container,以设置值,您只需简单地设置当前选定的项目。

没有必要进行迭代,你可以简单地做以下,

BackgroundsList.SelectedItem = current; 
2

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(); 
相关问题