如何从ListPicker Windows Phone 8.1 Silverlight中获取选中项的内容文本?

How to get the content text from the selected item ListPicker Windows Phone 8.1 Silverlight?

我在从 ListPicker 中的所选项目中获取文本时遇到问题,我找到了允许我这样做的代码

var content = ((ListPickerItem)CursoLista.SelectedItem).Content;

和我的 XAML:

<toolkit:ListPicker x:Name="CursoLista" Header="Curso" ItemsSource="{Binding}">
                    <toolkit:ListPicker.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <toolkit:ListPickerItem Content="{Binding Curso}"/>
                            </StackPanel>
                        </DataTemplate>
                    </toolkit:ListPicker.ItemTemplate>
                </toolkit:ListPicker>

如您所见,内容是从我的服务器绑定到一个列表:

private void Cliente_ProfessorRetrieveCompleted(object sender, Service.ProfessorRetrieveCompletedEventArgs e)
    {

        CursoLista.ItemsSource = e.Result;

但是当我尝试这样做时,我有一个例外:

Additional information: Unable to cast object of type 'FaculdadeGuararapes.Service.ListaProfessor' to type 'Microsoft.Phone.Controls.ListPickerItem'.

FaculdadeGuararapes.Service.ListaProfessor 这是来自我的网络服务器的名单!

首先,如果你的e.Result是一个字符串列表,你在后面的代码中设置了CursoLista.ItemsSource,你不需要在[=23=中添加ItemsSource ].接下来,如果你想检索单个选定的项目,只需固定到 SelectionChanged 事件。此外,可能没有必要添加 <DataTemplate>DataTemplate 仅在您想要自定义布局或绑定到 class.

时才需要
<toolkit:ListPicker x:Name="CursoLista" Header="Curso" SelectionChanged="CursoLista_SelectionChanged">
</toolkit:ListPicker>

并在后面的代码中处理它:

    private void CursoLista_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
         string selectedString = (sender as ListPicker).SelectedItem as string;
    }