从listPicker中获取选定的内容

本文关键字:listPicker 获取 | 更新日期: 2023-09-27 18:04:47

我找不到一种方法来获取和显示当前选中项目的内容,这里是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…"行:

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

从listPicker中获取选定的内容

尝试使用下面的代码

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);
}