2013-06-30 33 views
2

我使用列表框选择从列表框中选择一个项目,但我选择它,它产生了一个卑劣的exception.Here我的代码是: `列表框选择事件错误

<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(); 
     } 

`我不不知道我在哪做错误请引导我。我附上了它的图像,让你更清楚。 enter image description here谢谢!

回答

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(); 
} 
+0

,如果这是你的答案,然后亲切地选择它作为答案,所以没有人会得没有解释再次读取整个问题 – Shaharyar

+1

只是一段代码是没有用的。 – svick