MFC 将数据从 CViewTree 传递到 CFormView

MFC pass data from CViewTree to CFormView

本文关键字:CFormView CViewTree 数据 MFC      更新时间:2023-10-16

我有一个基于 CView 类的 MFC 应用程序。

我需要将数据在CViewTree之间传递到主视图

pDocTemplate = new CSingleDocTemplate(
    IDR_MAINFRAME,
    RUNTIME_CLASS(CMFCApplication1Doc),
    RUNTIME_CLASS(CMainFrame),       // <-- the CViewTree  is here
    RUNTIME_CLASS(CMFCApplication1View)); // <-- the main view (CFormView) is here

有什么建议吗?

定义您自己的消息,然后使用 AfxGetApp()->m_pMainWnd->SendMessage(MY_MESSAGE) .处理 CFormView (CMainView ??( 中的MY_MESSAGE,并在必要时强制转换为派生的 CFormView。

一个一般的例子 - 在"屠宰"你的主应用程序之前,在虚拟项目中尝试它。

1a( 将数据放在文档类中。每当修改数据时,调用 UpdateAllViews。

1b(添加一个特殊功能,从任何地方抓取文档在你的应用中。

// Data class
class Item : public CObject
{
    // your data here
};
class MyDocument : public CDocument
{
public:
    // Get the document from 'anywhere' for SDI projects
    // See:
    // http://asg.unige.ch/Past/fuentes/Mfc/HowTo_8.html
    // http://forums.codeguru.com/showthread.php?473808-MFC-Doc-View-How-to-get-the-active-document-anywhere-in-my-application
    static MyDocument* GetDoc()
    {
        auto frame = (CFrameWnd*)(AfxGetApp()->m_pMainWnd);
        return (MyDocument*)frame->GetActiveDocument();
    }
    static const int HintItemAdded = 1;
    // Add other hint constants here
    // Data functions
    void AddItem(Item const& item)
    {
        m_items.Add(item);
        // Call this if you need it    
        SetModifiedFlag();
        // Notify views that data has changed (via CView::OnUpdate)
        UpdateAllViews(nullptr, HintItemAdded,
            &m_items[m_items.GetUpperBound()]);
    }
    // Functions for inserting, updating, getting, removing data, etc.
private:
    CArray<Item> m_items;  // data
};

2( 使用文档操作命令处理程序中的数据:

// This handler could be in the document, a view (use GetDocument to get
// doc), frame (use GetActiveDocument to get doc), etc. If outside of
// those, use your special 'anywhere' function
void SomeClass::OnAddItemCommandHandler()
{
   CAddItemDlg dlg; // dialog that allows user input
   if (dlg.DoModal() == IDOK)
   {
      // use the 'anywhere' function
      auto doc = MyDocument::GetDoc();
      // use the user input to create new item and pass it to
      // the document
      doc->AddItem(dlg.GetNewItem());
   }
}

3( 确保您的视图具有 OnUpdate 处理程序。这被调用 CDocument::UpdateAllViews函数。

class MyView : public CFormView
{
    void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) override
    {
        CFormView::OnUpdate(pSender, lHint, pHint);
        // Just added a new item. pHint points to the new item
        if (lHint == MyDocument::HintItemAdded)    
        {
            auto newItem = (Item*)(pHint);
            // Add the new item to a list box
            m_listBox.AddString(newItem.GetText());
        }
   }
   CListBox m_listBox;
}