Setting selected item on Listbox in Silverlight - Windows Phone 7
I have a databound Listbox bound to a generic list as follows (Provider is a very simple class that just includes a single property (Name).
ProviderList = new List<Provider>();
//Populate list
Providers.ItemsSource = ProviderList;
I can save the selected item with no problem but I can't manage to set the selected item from code afterwards. I am trying to do so as follows:
int x = Providers.Items.IndexOf((Provider)_Settings["provider"]);
However IndexOf()
is alwa开发者_运维技巧ys returning -1. If I inspect both Providers.Items[1] and _Setting["provider"] at runtime using the immediate window they both return
{StoreRetrieveData.Provider}
Name: "Greenflag"
Am I doing something wrong (well clearly I am)?
Is there any chance you are comparing two different objects with same value? Can you try the following code instead:
Provider provider = (Provider)_Settings["provider"];
items.OfType<Provider>().Where(p => p.Name.Equals(provider.Name));
Use:
ListBox.Items
.OfType<ColumnDescriptor>()
.FirstOrDefault(c =>
String.Equals(
c.Name,
((Provider)_Settings["provider"]).Name,
StringComparison.Ordinal));
You might have to overload Equals and the == operator of your Provider class for this to work. Otherwise your comparison will fail if the objects are different instances. See http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
精彩评论