Fishcake
Fishcake

Reputation: 10754

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 always 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)?

Upvotes: 0

Views: 1028

Answers (3)

Jonas Van der Aa
Jonas Van der Aa

Reputation: 1461

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

Upvotes: 1

abatishchev
abatishchev

Reputation: 100238

Use:

ListBox.Items
    .OfType<ColumnDescriptor>()
    .FirstOrDefault(c =>
        String.Equals(
            c.Name,
            ((Provider)_Settings["provider"]).Name,
            StringComparison.Ordinal));

Upvotes: 1

decyclone
decyclone

Reputation: 30810

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

Upvotes: 1

Related Questions