0

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

2 回答 2

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)
            .....
            ....
      }
    }
于 2013-06-25T11:42:42.300 回答
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());
     }
}
于 2013-06-25T14:05:35.933 回答