This project has moved. For the latest updates, please go here.
1
Vote

ListPicker Fires SelectionChanged Event before Initialization

description

A simple ListPicker with 2 string options, as shown in the samples, when the event handler is added to a page and this page is navigated to, the event Fires before object initialization, causing NullReferenceException over that exact listPicker object.

XAML

...
                <tk:ListPicker x:Name="listTheme" 
                               Header="Background"
                               Margin="12,0,12,12"
                               SelectionChanged="listTheme_SelectionChanged">    
                    
                    <System:String>Dark</System:String>
                    <System:String>Light</System:String>
                </tk:ListPicker>
...

CS

private void listTheme_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listTheme.SelectedItem != null)
            {
                e.AddedItems[0].ToString();
            }
        }
    }
The exception is thrown when navigating to the page containing the listPicker, showing that "listTheme" is in fact 'null'.
Sender isn't null but doesn't have a SelectedItem.

comments

AntoniDol wrote Aug 19, 2014 at 2:48 PM

Workaround: keep track of initialization yourself:

public bool init = false;

InitializeComponent();
listSomething.SelectedIndex = appSettings.Something;
init = true;

private void SomethingChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        ListPicker lst = sender as ListPicker;
        if (init)
        {
            appSettings.AddOrUpdateValue("Something", lst.SelectedIndex); 
        }
    }