选择ListBoxItem的内容时出现InvalidCastException

时间:2010-12-29 05:45:32

标签: c# visual-studio-2010 windows-phone-7 listboxitem

我的ListBoxItems包含多个TextBox,如下所示:

<ListBox Name="myList" SelectionChanged="myList_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ListBoxItem>
                        <ListBoxItem.Content>
                            <StackPanel Orientation="Vertical">

                                <TextBlock Name="nameTextBlock" 
                                       Text="{Binding Name}" 
                                       />

                                <TextBlock Name="ageTextBlock" 
                                       Text="{Binding Age}" 
                                       />

                                <TextBlock Name="genderTextBlock" 
                                       Text="{Binding Gender}" 
                                       />

                                <TextBlock Name="heightTextBlock" 
                                       Text="{Binding Height}" 
                                       />

                            </StackPanel>
                        </ListBoxItem.Content>
                    </ListBoxItem>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

单击某个项目时,我希望每个TextBlock在相应的键下保存到IsolatedStorage。现在,我最接近这种方法的是:

private void mysList_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListBoxItem lbi = (ListBoxItem)myList.SelectedItem;
        appSettings["name"] = (string)lbi.Content;
    }

但是,点击后我得到一个InvalidCastException。据我了解,这主要是因为我试图将所有四个文本框转换为单个字符串(或类似的东西)。那么如何在ListBoxItem中将每个TextBox的文本字段独立保存为IsolatedStorage键/值?再次感谢。

1 个答案:

答案 0 :(得分:1)

当您通过设置ListBox媒体资源填充ItemsSource时,SelectedItem会引用您的class object,而不是ListBoxItem

例如,您已将ObservableCollection<Person>分配给ItemsSource

以下代码可以解决问题:

private void mysList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Person p = (Person)myList.SelectedItem;
    appSettings["name"] = String.Format("{0}, {1}, {2}, {3}", p.Name, p.Age, p.Gender, p.Height);
}