【问题标题】:Windows Phone 7: ListBox SelectionChanged eventWindows Phone 7:ListBox SelectionChanged 事件
【发布时间】:2013-08-09 17:47:03
【问题描述】:

我是 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”。

【问题讨论】:

  • ListBox 的 ItemsSource 是什么?您必须将其转换为对象的类型。例如,如果源是 List,那么您必须将 SelectItem 强制转换为 myClass。
  • 我已经编辑了代码,我做错了什么?

标签: c# listbox selecteditem


【解决方案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

【讨论】:

    【解决方案2】:

    您选择的项目不是 ListBoxItem,但它实际上是您通过 ItemSource 绑定到 ListBox 的任何对象的类型。因此,将其转换为 ListBoxItem 会返回一个空对象。

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

    【讨论】:

    • 所以我无法检测到选定的项目/对象?
    • 您选择的项目将是返回的任何对象类型:parser.LevelCollection
    • 看起来类型是:LocalXmlParsing.XMLParser。
    • 是的,但是如何转换/解析它?
    • 您需要使用解析器将您的 XML 解析为具体类型。这样的事情应该会有所帮助:stackoverflow.com/questions/14226473/c-sharp-parsing-xml-file
    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多