1

在我的课堂上,我为 ListBoxItem 编写了双击事件。单击列表框的条目时,它应该只返回该特定条目。但在我的情况下,虽然我点击了单个条目,但所有条目都被返回并发生了“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"/>
4

3 回答 3

4

ListBox 将其项目隐式包装到ListBoxItem. 尝试强制sender转换ListBoxItem然后获取其Content属性

于 2013-06-25T06:50:17.597 回答
0

尝试使用 as Operator 而不是 Direct cast,并在进一步处理之前包含 null 检查

于 2013-06-25T07:03:47.840 回答
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)
        { }
     }
于 2013-06-25T15:01:53.653 回答