The Silverlight Toolkit for Windows Phone 7 packs a really nice collection of controls that one could use for Windows Phone Silverlight apps. Most of these controls are ready to use out-of-the-box, not present in the default developer toolset & simply make life easier by mimicking OS features in how the controls work. You could get the latest toolkit from (here).
One of the controls that I was recently using was the ListPicker. Simply put, these are replacements for the clunky combo-boxes in the shiny Windows Phone world. Dropdowns with multiple options (pop-out or fullscreen) are seen everywhere in the core OS and the Toolkit Listpicker works identically. Here are two posts that detail the use of the ListPicker control:
http://www.windowsphonegeek.com/articles/listpicker-for-wp7-in-depth
However, you may be in for a little surprise as you bind data to the ListPicker control. The ListPicker works under the presumption that there is always an active selection. This results in the ListPicker trying to make a default selection as the page/control initializes or as the bound data lists changes in the background. Now, if you have a “SelectionChanged” event handler wired up to the ListPicker control, it will fire the first time the control binds itself to data. This means that the associated event handler will execute it’s code; this catches a few folks by surprise .. yes, I am one.
So, how does one get around the problem? Simple, learn to ignore the raised “SelectionChanged” event when you don’t care during initialization, irrespective of when data binding happens. Here’s the code:
private void SomeListPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Make sure we don't handle the event during initiation.
if (e.RemovedItems != null && e.RemovedItems.Count > 0)
{
if (this.SomeListPicker.SelectedItem != null)
{
// Do actual stuff.
}
}
}
Hope this was helpful.
Adios!
An alternative. Bind to the ListPicker in XAML and do NOT add the SelectionChanged event on the ListPicker in XAML. Instead, on the Page Loaded Event add the handler to the SelectionChanged. If you have more than one, create a method to add handlers to all your controls within the Loaded Event. 🙂
Indeed it was helpful, thank you!
You’re welcome 🙂 Thanks for the comment!
Thanx, man, it worked! )
Finally a working solution and a simple one at that! Thanks man!
THANK YOU. This was driving me insane.
THANK YOU. This helped a lot!
Also unbelievable, this issue hasn’t been fixed for years..