【问题标题】:NullReferenceException when Double Clicked on ListBox entry双击 ListBox 条目时出现 NullReferenceException
【发布时间】:2013-06-25 22:05:35
【问题描述】:

我在 wpf 应用程序中有一个 listBox,它包含两个条目。我已经为它编写了双击事件函数。但是当我单击任何单个条目时,它会显示NullReferenceException。例外是在线 - if (listBox1.SelectedItem != null)

我只想要一个我会点击的条目。我应该如何进行?

我的双击事件如下:

private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        //Submit clicked Entry
        if (listBox1.SelectedItem != null)
        {
            Harvest_TimeSheetEntry entryToPost = (Harvest_TimeSheetEntry)listBox1.SelectedItem;
            if (!entryToPost.isSynced)
            {
                //Check if something is selected in selectedProjectItem For that item
                if (entryToPost.ProjectNameBinding == "Select Project")
                    MessageBox.Show("Please Select a Project for the Entry");
                else
                    Globals._globalController.harvestManager.postHarvestEntry(entryToPost);
            }
            else
            {
                //Already synced.. Make a noise or something
                MessageBox.Show("Already Synced;TODO Play a Sound Instead");
            }
        }
        else
        {
            throw new NullReferenceException("Entry does not exist");
        }

     }

我将事件处理程序分配为,

InitializeComponent();
listBox1.MouseDoubleClick += new MouseButtonEventHandler(listBox1_MouseDoubleClick);

【问题讨论】:

  • 你能显示 listBox1 标记吗?
  • 这是 WPF?对我来说看起来像 WinForms。为什么不通过利用数据绑定和对绑定集合进行操作来获取 WPF 的功能呢?
  • 是的。我试过了。它在我提到的第一行抛出异常。
  • @Marius 没有什么可以阻止程序员使用 WPF 中的代码,但不鼓励使用 MVVM。
  • listBox1 标记-

标签: c# wpf nullreferenceexception double-click listboxitem


【解决方案1】:

尝试添加这一行而不是直接使用 listBox1:

private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        //Submit clicked Entry
         if(sender is ListBox)
         {
            var listBoxRef = sender as ListBox;
            ...
            if (listBoxRef.SelectedItem != null)
            .....
            ....
      }
    }

【讨论】:

  • 我试过了,但仍然显示空引用异常。我认为,SelectedItem 存在问题,因为当我放置断点和调试时,它显示为 null。
【解决方案2】:

我发现了如下内容。试试看。它将在双击时显示选定的项目文本。您可以根据您的要求对其进行修改。

void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
     int index = this.listBox1.IndexFromPoint(e.Location);
     if (index != System.Windows.Forms.ListBox.NoMatches)
     {
         MessageBox.Show(index.ToString());
     }
}

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    相关资源
    最近更新 更多