Question

I have a ListPicker in my xaml code, and it contains more than ListPickerItem, I want to show a pushpin on my map according to which ListPickerItem is selected.

That's my XAML:

<toolkit:ListPicker Foreground="white" Opacity="0.9" x:Name="OptionSelection" Margin="0,18,0,0" SelectionChanged="Picker">
                    <toolkit:ListPickerItem Tag="1" x:Name="Option1" Content="Item1"/>
                    <toolkit:ListPickerItem Tag="2" x:Name="Option2" Content="Item2"/>
                    <toolkit:ListPickerItem Tag="3" x:Name="Option3" Content="Item3"/>
                </toolkit:ListPicker>

And here is my CS code for the SelectionChanged event:

private void Picker(object sender, SelectionChangedEventArgs e)
        {

            var tag = ((ListPickerItem)OptionSelection.SelectedItem).Tag;

            if (tag.Equals(1))
            {
                MessageBox.Show("Item1 selected"); //I will replace this with my geolocation function later.
            }

        }

Mainly I want to know how to apply if statement on my code, that will help me add the geolocation function based on selected item.

Was it helpful?

Solution

Your if statement to execute code based on user selection looks fine, except value of Tag in this case is a string so you should've compared it to another string ("1") instead of integer (1).

The exception you got seems thrown when value of SelectedItem is null. You can try to add simple checking at the beginning of the function to handle this condition properly and avoid NullReferenceException :

private void Picker(object sender, SelectionChangedEventArgs e)
{
    if(OptionSelection.SelectedItem == null)
    {
        //do some logic to handle null condition
        //or simply exit the function if there is no logic to be done :
        return;
    }
    var tag = ((ListPickerItem)OptionSelection.SelectedItem).Tag;
    //value of Tag is a string according to your XAML
    if (tag.Equals("1"))
    {
        MessageBox.Show("Item1 selected");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top