Learning Hub Search Ctrl K

MFC › 3. Document/View Architecture

Documents, Views and Frames

The document/view model and how the pieces connect.

intermediate #mfc#document-view#cdocument#cview#doctemplate#updateallviews#onupdate

Explanation

The document/view architecture separates data from its presentation:

Class Responsibility
CDocument owns the data; loads/saves it (Serialize); tracks the modified flag
CView displays the document and turns user input into changes; many views can show one document
CFrameWnd the window frame around a view (menu, toolbar, status bar)
CDocTemplate (CSingleDocTemplate / CMultiDocTemplate) glues the three classes and the resource ID together

The template is registered in InitInstance:

AddDocTemplate(new CSingleDocTemplate(IDR_MAINFRAME,           // menu, accelerators, icon, strings
                                      RUNTIME_CLASS(CMyDoc),
                                      RUNTIME_CLASS(CMainFrame),
                                      RUNTIME_CLASS(CMyView)));

MFC then provides File New/Open/Save/Save As/Close/Print/MRU list for free.

The update cycle (the heart of the pattern):

  1. The user acts in a view (click, key).
  2. The view changes the data through GetDocument().
  3. The document calls SetModifiedFlag() and UpdateAllViews(pSender, lHint, pHint).
  4. Each view’s OnUpdate runs (default: Invalidate()), then OnDraw repaints.

Key members: CDocument::OnNewDocument, OnOpenDocument, DeleteContents (reset the data), Serialize, IsModified; CView::OnDraw(CDC*), OnInitialUpdate, OnUpdate, GetDocument.

Example

A document holding points, and a view that draws them and adds a point on click:

#include <afxwin.h>
#include <afxext.h>
#include <afxtempl.h>

class CScribbleDoc : public CDocument {
    DECLARE_DYNCREATE(CScribbleDoc)
public:
    CArray<CPoint, CPoint> m_points;

    void AddPoint(CPoint pt) {
        m_points.Add(pt);
        SetModifiedFlag();                       // "Save changes?" prompt on close
        UpdateAllViews(nullptr);                 // tell every view
    }
    void DeleteContents() override {             // called for New, Open and Close
        m_points.RemoveAll();
        CDocument::DeleteContents();
    }
    void Serialize(CArchive& ar) override {
        m_points.Serialize(ar);                  // CArray<CPoint> knows how to save itself
    }
};
IMPLEMENT_DYNCREATE(CScribbleDoc, CDocument)

class CScribbleView : public CView {
    DECLARE_DYNCREATE(CScribbleView)
protected:
    CScribbleDoc* GetDocument() const { return static_cast<CScribbleDoc*>(m_pDocument); }

    void OnDraw(CDC* pDC) override {             // never paint outside OnDraw
        CScribbleDoc* pDoc = GetDocument();
        ASSERT_VALID(pDoc);
        for (INT_PTR i = 0; i < pDoc->m_points.GetSize(); ++i) {
            CPoint p = pDoc->m_points[i];
            pDC->Ellipse(p.x - 3, p.y - 3, p.x + 3, p.y + 3);
        }
    }
    void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) override {
        CView::OnUpdate(pSender, lHint, pHint);  // default behavior: Invalidate()
    }
    afx_msg void OnLButtonDown(UINT nFlags, CPoint point) {
        GetDocument()->AddPoint(point);          // the view edits through the document
        CView::OnLButtonDown(nFlags, point);
    }
    DECLARE_MESSAGE_MAP()
};
IMPLEMENT_DYNCREATE(CScribbleView, CView)
BEGIN_MESSAGE_MAP(CScribbleView, CView)
    ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()

class CScribbleApp : public CWinApp {
public:
    BOOL InitInstance() override {
        CWinApp::InitInstance();
        SetRegistryKey(_T("Demo"));
        LoadStdProfileSettings(4);               // recent-file list
        AddDocTemplate(new CSingleDocTemplate(
            IDR_MAINFRAME,
            RUNTIME_CLASS(CScribbleDoc),
            RUNTIME_CLASS(CFrameWnd),
            RUNTIME_CLASS(CScribbleView)));

        CCommandLineInfo cmdInfo;
        ParseCommandLine(cmdInfo);               // handles "File New" and "open this file"
        if (!ProcessShellCommand(cmdInfo)) return FALSE;
        m_pMainWnd->ShowWindow(SW_SHOW);
        m_pMainWnd->UpdateWindow();
        return TRUE;
    }
};
CScribbleApp theApp;

Common pitfalls

  • Storing document data in the view loses it when the view is closed or when a second view opens. Keep data in the document.
  • Forgetting SetModifiedFlag() means no “Save changes?” prompt and the Save command stays disabled.
  • Reset all data in DeleteContents, not only in OnNewDocument; Open reuses the same document object.
  • Painting outside OnDraw (e.g., directly in a mouse handler with GetDC) isn’t redrawn when the window is uncovered. Update the data, then Invalidate().
  • UpdateAllViews(NULL) repaints everything; pass pSender plus a hint to refresh only what changed.
  • The IDR_MAINFRAME resource ID must exist as a menu, an icon, an accelerator table and a document string ("\nScribble\nScribble\n..."), or the template fails to load.

Win32 vs MFC

Raw Win32 has no document concept: you decide where data lives, handle WM_PAINT and write all file handling and the MRU list yourself. Document/View trades flexibility for ready-made plumbing. Many modern apps keep the same idea as “model + view”, often without MFC’s document class.

Exercises

1. Two views show the same document. One view edits it: what makes the other view repaint?

The document calls UpdateAllViews, which calls OnUpdate on every attached view (the default OnUpdate invalidates the window, causing OnDraw).