Question

I have a SelectionChanged event in a ListPicker within one of my application Pages that fires multiple times before the page is loaded. This is really inconvenient for me as when an item is selected, a MessageBox is displayed (and other actions will be performed). The MessageBox is displayed twice every time the page is NavigatedTo. How can I fix this?

XAML

<toolkit:ListPicker x:Name="ThemeListPicker" Header="Theme"
                    ItemTemplate="{StaticResource PickerItemTemplate}" 
                    SelectionChanged="ThemeListPicker_SelectionChanged"/>

XAML.CS

private void ThemeListPicker_SelectionChanged(object sender,
                                              SelectionChangedEventArgs e)
{
   if(ThemeListPicker.SelectedIndex != -1)
   {
       var theme = (sender as ListPicker).SelectedItem;

       if (index == 0)
       {
          Settings.LightTheme.Value = true;
          MessageBox.Show("light");
       }
       else
       {
           Settings.LightTheme.Value = false;
           MessageBox.Show("dark");
       }
   }                            
}
Was it helpful?

Solution

well, that's how a listpicker behaves, what best you can do is instead of making ThemeListPicker_SelectionChanged make a parent stackpanel inside the datatemplate somewhat like this

<Listpicker.ItemTemplate>
<DataTemplate x:Name="PickerItemTemplate"> 
               <StackPanel tap="stk_Tap"> 
                    <TextBlock/> 
                </StackPanel> 
            </DataTemplate>
</Listpicker.ItemTemplate>
<Listpicker.FullModeItemTemplate>
            <DataTemplate x:Name="PickerFullModeItemTemplate"> 
                <StackPanel tap="stk_Tap"> 
                    <TextBlock/> 
                </StackPanel> 
            </DataTemplate>
<Listpicker.FullModeItemTemplate>

now use this tap stk_Tap to do your action as, this event would also get called every time the selection changed gets called but, it wont exhibit the buggy behavior like that of selection changed event.

hope this helps.

OTHER TIPS

Attach the SelectionChanged event after the ListPicker is Loaded.

        ...
        InitializeComponent();
        YourListPicker.Loaded += YourListPicker_Loaded;
        ...

    private void YourListPicker_Loaded(object sender, RoutedEventArgs e)
    {
        YourListPicker.SelectionChanged += YourListPicker_SelectionChanged;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top