views:

48

answers:

2

All that i'm trying to do is to compare, for each value in a listbox, its value with a chosen one and then set the match index as selected. For some reason the exception in the title is raised. I don't understand why though. Code:

            foreach(SurfaceListBoxItem n in BackgroundsList.Items)
        {
            if (n.ToString() == current) BackgroundsList.SelectedItem = n;
        }

Thanks!

+2  A: 

In WPF, List.Items does not necessarily contain collection of ListBoxItem, instead it only contains data values, and the Item Container of the data is derived, to set value, you must simply set current to selected item.

There is no need to iterate, you can simply do following,

BackgroundsList.SelectedItem = current;
Akash Kava
+1  A: 

The C# foreach statement does an implicit cast for you from the type of the element returned by Items to the specified SurfaceListBoxItem type. At runtime the returned string can not be casted to SurfaceListBoxItem. You can solve this by using var instead of SurfaceListBoxItem

foreach(var n in BackgroundsList.Items)
{
    if (n.ToString() == current) BackgroundsList.SelectedItem = n;
}

Or, of course, you can use LINQ:

BackgroundsList.SelectedItem = (
    from n in BackgroundList.Items
    where n.ToString() == current
    select n).FirstOrDefault();
Steven