c# - 列表框选择事件错误

标签 c# .net wpf nullreferenceexception

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

 <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谢谢!

最佳答案

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

关于c# - 列表框选择事件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17389975/

相关文章:

c# - LINQ 查询出生日期以获取年龄

c# - 为什么我的进度条不起作用?

wpf - 将 Windows 7 屏幕键盘合并到 WPF 应用程序中

c# - asp.net 认证看机器名

C# 字符串 - 为什么 null 给我的结果与 ""不同?

c# - 如何在 Android 中使用信号器

c# - 如何使用 lambda 表达式从嵌套集合中获取叶节点

.Net - 检测所需标识符是否为关键字

c# - .net 集合内存优化 - 这种方法有效吗?

wpf - ListView 选择颜色