Dan
Dan

Reputation: 205

InvalidCastException from selecting ListBoxItem's Contents

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.

Upvotes: 1

Views: 501

Answers (1)

decyclone
decyclone

Reputation: 30840

When you populate your ListBox by setting ItemsSource property, SelectedItem will have a reference to your class object, not ListBoxItem.

For example you have assigned ObservableCollection<Person> to ItemsSource,

Following code will do the trick:

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

Upvotes: 1

Related Questions