2

我正在使用列表框从列表框中选择一个项目,但是当我选择它时,它会生成一个不正当的异常。我的代码是:`

 <ListBox Grid.Row="1"  SelectionChanged="PrintText" Background="DarkGray" Visibility="Collapsed"  Height="Auto" HorizontalAlignment="Left" Margin="156,36,0,0" Name="listBox1" VerticalAlignment="Top" Width="191" UseLayoutRounding="True" />

 void PrintText(object sender, SelectionChangedEventArgs args)
        {
            ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
            String a =  lbi.Content.ToString();
           Window1 neww = null;
            neww = new Window1();
            neww.Show();
        }

`我不知道我在哪里做错了请指导我。我附上了它的图像,让你更清楚。在此处输入图像描述谢谢你!

4

1 回答 1

1
void PrintText(object sender, SelectionChangedEventArgs args)
{
  object item = listBox1.SelectedItem;

  if (item == null) {
    txtSelectedItem.Text = "No item currently selected.";
  } else {
    txtSelectedItem.Text = item.ToString();
  }

  // ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
  //  String a =  lbi.Content.ToString();
  Window1 neww = null;
  neww = new Window1();
  neww.Show();
}
于 2013-06-30T11:52:28.057 回答