双击ListBox条目时出现NullReferenceException

本文关键字:NullReferenceException ListBox 双击 | 更新日期: 2023-09-27 18:19:59

我在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);

双击ListBox条目时出现NullReferenceException

尝试直接使用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)
            .....
            ....
      }
    }

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

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