我是XAML和Windows Phone 7 SDK的新手。我正在开发一个Windows Phone 7应用程序,我不知道如何从ListBox中检测所选项目。我正在使用全景模板,这是我的代码:
<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>
和C#代码:
MessageBox.Show(Elementary.SelectedItem.ToString()); //returns "LocalXmlParsing.XMLParser"
我正在使用XMLParser,应用初始化代码:
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;
当我尝试检测SelectedItem
时,ListBox会返回此字符串:“LocalXmlParsing.XMLParser”。
答案 0 :(得分:1)
您选择的项目不是ListBoxItem,但它实际上是通过ItemSource绑定到ListBox的任何对象的类型。因此将它转换为ListBoxItem会返回一个null对象。
ListBox.ItemsSource = new List<myObject>() { new myObject(), new myObject() };
ListBox.SelectedIndex = 1;
var selectedObject = ListBox.SelectedItem as myObject;
答案 1 :(得分:1)
看起来您正在使用名为“LocalXmlParsing”的Nokia's Sample project。您仍然可以使用您的代码,但如果您想要检测SelectedItem
,您应该使用以下内容:
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