我正在使用列表框从列表框中选择一个项目,但是当我选择它时会产生一个不足的异常。这里我的代码是: `
<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();
}
`我不知道我在哪里做错了请指导我。我附上了它的图像,让你更清楚。 谢谢!
答案 0 :(得分: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();
}