MFC:从 ChildView 访问 CMainFrame 的 CImageList

MFC : accessing CMainFrame's CImageList from ChildView

我正在尝试将图像添加到工具栏的图像列表中,它是 CMainFrame 的成员

startStopPicture.LoadBitmapW(IDB_STOP_PIC);
m_ToolBar.GetToolBarCtrl().GetImageList()->Add(&startStopPicture, reinterpret_cast<CBitmap*>(NULL)); 

startStopPicture.DeleteObject();

startStopPicture.LoadBitmapW(IDB_START_PIC);
m_ToolBar.GetToolBarCtrl().GetImageList()->Add(&startStopPicture, reinterpret_cast<CBitmap*>(NULL)); 

然后我需要从子视图访问这个图像列表。我正在尝试这样做

CMainFrame* mainFrame = dynamic_cast<CMainFrame*>(GetParentFrame());

CImageList* imList = mainFrame->m_ToolBar.GetToolBarCtrl().GetImageList();

但是我在主机方法中添加的那些图片现在不存在了。如何解决这个问题?

我假设你的CBitmap startStopPicture is a local variable, since you neither mentioned otherwise or preceded the variable name with any class-like-identifier. Afterwards you try to store via CImageList::Add引用了局部变量

您需要做的是分配 CBitmap - new CBitmap 或将 startStopPicture 变量作为成员添加到您的 class。

如果您选择分配变量并且不必跟踪 CBitmap,您可以使用 std::vector<std::unique_ptr<CBitmap> > 作为 class-成员。

如果将局部变量CBitmap存储在CImageList中,图像将不会显示。

示例:

//class declaration
private:
    std::vector<std::unique_ptr<CBitmap> > m_vLoadedBitmaps;
};

void CMyCtrl::SetBitmaps(CImageList &imgList)
{
    CBitmap *bmpDelete = new CBitmap();
    bmpDelete->LoadBitmapW(IDB_DELETE);
    m_vLoadedBitmaps.push_back(std::unique_ptr<CBitmap>(bmpDelete));

    imgList.Add(bmpDelete, static_cast<CBitmap*>(NULL));
}

我还建议在变量的所有者 class 中加载图像。如果需要,还有 SendMessage.