C#WP8从listPicker中获取所选内容

时间:2013-03-20 13:42:27

标签: c# windows-phone-8 listpicker

我找不到获取和显示当前所选项目内容的方法,这里是XAML:

<toolkit:ListPicker Name="lp" Header="Network" SelectionChanged="selectionChanged">
            <toolkit:ListPickerItem Content="aaa" />
            <toolkit:ListPickerItem Content="bbb" />
</toolkit:ListPicker>

以及其余代码:

private void selectionChanged(object sender, SelectionChangedEventArgs e)
    {
        try
        {
            if (e.RemovedItems != null && e.RemovedItems.Count > 0)
            {
                if (this.lp.SelectedItem != null)
                {
                    var selectedItem = (sender as ListPicker).SelectedItem;
                    int selindex = lp.SelectedIndex; //just for testing
                    MessageBox.Show(selindex.ToString()); //just for testing
                    string text = (lp.SelectedItem as ListBoxItem).Content.ToString();
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

它在“string text ...”行中给了我这个例外:

  

未将对象引用设置为对象的实例

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码

try
{
   if (e.RemovedItems != null && e.RemovedItems.Count > 0)
   {
        if (this.mode.SelectedItem != null)
        {
             var selectedItem = (sender as ListPicker).SelectedItem as ListPickerItem;
             int selindex = mode.SelectedIndex; //just for testing
             MessageBox.Show(selindex.ToString()); //just for testing
             string text = (selectedItem as ListPickerItem).Content.ToString();
        }
   }
}
catch (Exception ex)
{
       MessageBox.Show(ex.Message);
}