2014-04-07 43 views
1

我在我的xaml代码中有一个ListPicker,它包含的不止是ListPickerItem,我想根据选择的ListPickerItem在我的地图上显示一个图钉。如何在windows phone 8中基于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语句如何应用在我的代码,这将有助于我根据选定的项目添加地理定位功能。

+0

什么问题吗? – Sajeetharan

+0

它给出了一个例外,这里详细说明 DataBoundApp3.DLL中发生了类型'System.NullReferenceException'的异常,但未在用户代码中处理 附加信息:未将对象引用设置为对象的实例。 – user3269487

回答

0

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

SelectedItem的值为空时,似乎抛出了异常。您可以尝试在函数的开头添加简单的检查,以妥善处理这一情况,避免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"); 
    } 
} 
+0

看来问题的一半已经解决了!现在它给了我一个例外,即选项选择=空(你的代码没有编辑) – user3269487

+0

我已经替换:if(OptionSelection.SelectedItem == null)with:if(OptionSelection == null),这对我工作感谢您的帮帮我 ! – user3269487

+0

不客气!如果它适合你,请不要忘记接受这个答案。更多信息:[如何接受答案的工作?](http://meta.stackexchange.com/a/5235) – har07

相关问题