InvalidCastException from selecting ListBoxItem's Contents

Posted by Dan on Stack Overflow See other posts from Stack Overflow or by Dan
Published on 2010-12-29T05:45:31Z Indexed on 2010/12/29 5:54 UTC
Read the original article Hit count: 323

My ListBoxItems contain multiple TextBoxes like this:

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

When an item is clicked, I would like each TextBlock to be saved to IsolatedStorage under corresponding keys. Right now the closest I've gotten to this method is this:

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

But, when clicked I get an InvalidCastException. As I understand it, it's basically due to me trying to convert all four textboxes into a single string (or something like that). So how do I save each TextBox's text field independently within the ListBoxItem to an IsolatedStorage key/value? Thanks again in advance.

© Stack Overflow or respective owner

Related posts about c#

Related posts about visual-studio-2010