ListPicker SelectionChanged Event Called Multiple Times During Navigation

三世轮回 提交于 2019-12-11 23:28:47

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/20592301/listpicker-selectionchanged-event-called-multiple-times-during-navigation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!