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

时间:2015-10-22 04:44:17

标签: c# windows-phone

我这里有一个问题是从我的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>

如您所见,内容是从我的服务器绑定到List:

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

        CursoLista.ItemsSource = e.Result;

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

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

FaculdadeGuararapes.Service.ListaProfessor来自我的WebServer的列表!

1 个答案:

答案 0 :(得分:0)

首先,如果您的e.Result是字符串列表,并且您从代码中设置了CursoLista.ItemsSource,那么您就不需要在xaml中添加ItemsSource。接下来,如果您想要检索单个选定项目,只需固定到SelectionChanged事件即可。此外,可能没有必要添加<DataTemplate>。仅当您要自定义布局或绑定到类时,才需要DataTemplate

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