2014-04-07 38 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

相關問題