在我的课堂上,我为ListBoxItem编写了双击事件。单击listBox的条目时,它应仅返回该特定条目。但在我的情况下,虽然我点击了单个条目,但所有条目都被返回并且" InvalidCastException" occures。那么,我应该如何改变以获得单一条目。
这是双击事件代码:
private void ListBoxItem_DoubleClick(object sender, RoutedEventArgs e)
{
//Submit clicked Entry
Harvest_TimeSheetEntry entryToPost = (Harvest_TimeSheetEntry)sender;
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");
}
}
In xml:
<ListBox x:Name="listBox1" ItemsSource="{Binding}" Margin="0,131,0,59" ItemTemplateSelector="{StaticResource templateSelector}" ListBoxItem.MouseDoubleClick="ListBoxItem_DoubleClick"/>
答案 0 :(得分:4)
ListBox隐式将其项目包装到ListBoxItem
中。尝试将sender
转换为ListBoxItem
,然后获取其Content
属性
答案 1 :(得分:0)
尝试使用运算符而不是直接转换,并在进一步处理之前包括空值检查
答案 2 :(得分:0)
最后,它有效。
private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
//Submit clicked Entry
try
{
ListBoxItem item = (ListBoxItem)sender;
Harvest_TimeSheetEntry entryToPost = (Harvest_TimeSheetEntry)item.Content;
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");
}
}
catch (Exception)
{ }
}