双击ListBox条目时出现NullReferenceException

时间:2013-06-25 11:27:47

标签: c# wpf nullreferenceexception double-click listboxitem

我在wpf应用程序中列出了包含两个条目的box。我为它编写了双击事件功能。但是当我点击任何一个条目时,它会显示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");
        }

     }

我将eventhandler指定为,

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

2 个答案:

答案 0 :(得分: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)
            .....
            ....
      }
    }

答案 1 :(得分:0)

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

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