如何根据 Windows Phone 8 中的 ListPickerItem Select 执行功能



我的xaml代码中有一个ListPicker,它包含的不仅仅是ListPickerItem,我想在我的地图上显示一个图钉,根据它选择了ListPickerItem。

那是我的 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>

这是我的 SelectionChanged 事件的 CS 代码:

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

主要是我想知道如何在我的代码上应用 if 语句,这将有助于我根据所选项目添加地理位置功能。

根据用户选择执行代码的if语句看起来不错,但在这种情况下Tag的值是一个字符串,所以你应该将其与另一个字符串("1")而不是整数(1)进行比较。

当值 SelectedItem 为 null 时,您得到的异常似乎会引发。您可以尝试在函数的开头添加简单的检查,以正确处理这种情况并避免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");
    }
}

最新更新