类型';System.InvalidCastException';发生
本文关键字:发生 InvalidCastException System 类型 | 更新日期: 2023-09-27 18:19:42
在我的类中,我为ListBoxItem编写了双击事件。当单击listBox的条目时,它应该只返回该特定条目。但在我的情况下,尽管我点击了一个条目,但所有条目都会返回,并出现"InvalidCastException"。那么,我应该如何更改才能获得单个条目。
这是双击事件代码:
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"/>
ListBox将其项隐式包装到ListBoxItem
中。尝试将sender
强制转换为ListBoxItem
,然后获取其Content
属性
在进一步处理
最后,它成功了。
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)
{ }
}