2010-07-22 93 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(); 
相關問題