简体   繁体   中英

Windows Phone 7: ListBox SelectionChanged event

I'm new to XAML and Windows Phone 7 SDK. I'm developing an Windows Phone 7 application and I don't know how to detect selected item from the ListBox. I'm using panorama template, here is my code:

<controls:PanoramaItem Header="Basic">
   <ListBox Margin="0,0,-12,0" Name="MyListBox" SelectionChanged="Elementary_SelectionChanged">
      <ListBox.ItemTemplate>
         <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="0,0,0,17">
               <Image Height="100" Width="100" Source="{Binding LevelPassedImage}" Margin="12,0,9,0"/>
               <StackPanel Width="311">
                  <TextBlock Name="lvlName" x:Uid="Elementary{Binding LevelId}" Text="{Binding LevelName}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" />
                  <TextBlock Text="{Binding LevelPassed}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}" />
               </StackPanel>
            </StackPanel>
         </DataTemplate>
      </ListBox.ItemTemplate>
   </ListBox>
</controls:PanoramaItem>

And C# code:

MessageBox.Show(Elementary.SelectedItem.ToString()); //returns "LocalXmlParsing.XMLParser"

I'm using XMLParser, app initialization code:

var parser = LocalXmlParsing.XMLParser.Instance;

StreamResourceInfo strm = Application.GetResourceStream(new Uri("Levels/ElementaryLevels.xml", UriKind.Relative));
StreamReader reader = new StreamReader(strm.Stream);
string data = reader.ReadToEnd();
parser.DataToParse = data;
parser.ParseStateData();
MyListBox.ItemsSource = parser.LevelCollection;

When I'm trying to detect SelectedItem , ListBox returns me this string: "LocalXmlParsing.XMLParser".

Your selected item is not a ListBoxItem, but it's actually the type of whatever object you bound to the ListBox through the ItemSource. So casting it to a ListBoxItem is returning you a null object.

ListBox.ItemsSource = new List<myObject>() { new myObject(), new myObject() };
ListBox.SelectedIndex = 1;
var selectedObject = ListBox.SelectedItem as myObject;

It looks like you are using Nokia's Sample project called "LocalXmlParsing". You can still use your code, but if you want to detect SelectedItem you should use something like this:

LocalXmlParsing.Level selecteditem = (LocalXmlParsing.Level)myListBox.SelectedItem; //it will returns your element
MessageBox.Show(selecteditem.Id); //It will return the Id of SelectedItem (String). You should use yours: SelectedItem.MyElement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM