C# 双击列表框条目时出现NullReferenceException
我在wpf应用程序中创建了listBox,它包含两个条目。我已经为它编写了双击事件函数。但是当我单击任何一个条目时,它会显示C# 双击列表框条目时出现NullReferenceException,c#,wpf,nullreferenceexception,double-click,listboxitem,C#,Wpf,Nullreferenceexception,Double Click,Listboxitem,我在wpf应用程序中创建了listBox,它包含两个条目。我已经为它编写了双击事件函数。但是当我单击任何一个条目时,它会显示NullReferenceException。如果(listBox1.SelectedItem!=null) 我只想要一个我要点击的条目。我应该如何进行 我的双击事件如下所示: private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e) { //Submi
NullReferenceException
。如果(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);
尝试添加此行,而不是直接使用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());
}
}
你能显示listBox1标记吗?这是WPF?在我看来像WinForms。为什么不利用数据绑定和对绑定集合进行操作来获取WPF的功能呢?是的。我试过了。它在我提到的第一行抛出异常。@Marius没有任何东西阻止程序员在WPF中使用隐藏的代码,但不鼓励使用MVVM.listBox1标记-我试过了,但仍然显示空引用异常。我认为SelectedItem有问题,因为当我放置断点并调试时,它显示为null。