在theAppp中用某一个文档类关联了几个视图后,好象每个视图都对应了自己的文档,不知道如何用一个文档关联多个视图
当文档中数据变化时几个视图都相应的变化

解决方案 »

  1.   

    pDoc->UpdateAllViews可以根据文档的数据刷新所有的视图
      

  2.   

    默认的mdi实现, 是一个文档对象对应一个子框架窗口, 同时对应一个视图窗口。 
    但很多时候我们并不需要那么多的文档对象, 反倒是很需要“单一文档对象-多子框架窗口-多视图”这样的应用。
    给你个简单的方法实现:1. 从CMultiDocTemplate派生自己的DocTemplate类型, 加入一个数据成员
    protected:
    CDocument *m_pOnlyDoc;
    2. 改写CDocTemplate类的虚函数OpenDocumentFile,在其中不要每次都新建Document就行了:        CDocument *pDocument = NULL;
    BOOL bCreated = FALSE; if (m_pOnlyDoc != NULL)
    {
    pDocument = m_pOnlyDoc;
    }
    else
    {
    pDocument = CreateNewDocument();
    if (pDocument == NULL)
    {
    TRACE0("CDocTemplate::CreateNewDocument returned NULL.\n");
    AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);
    return NULL;
    }
    ASSERT_VALID(pDocument);
    pDocument->m_bAutoDelete = FALSE;
    m_pOnlyDoc = pDocument;
    bCreated = TRUE;
    }
    ASSERT_VALID(pDocument);

    CFrameWnd* pFrame = CreateNewFrame(pDocument, NULL);
    if (pFrame == NULL)
    {
    AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);
    delete pDocument;       // explicit delete on error
    return NULL;
    }
    ASSERT_VALID(pFrame);

    if (bCreated)
    {
    // create a new document - with default document name
    SetDefaultTitle(pDocument);

    // avoid creating temporary compound file when starting up invisible
    if (!bMakeVisible)
    pDocument->m_bEmbedded = TRUE;

    if (!pDocument->OnNewDocument())
    {
    // user has be alerted to what failed in OnNewDocument
    TRACE0("CDocument::OnNewDocument returned FALSE.\n");
    pFrame->DestroyWindow();
    return NULL;
    }

    // it worked, now bump untitled count
    m_nUntitledCount++;
    }
    else
    {
    // open an existing document
    /*
    CWaitCursor wait;
    if (!pDocument->OnOpenDocument(lpszPathName))
    {
    // user has be alerted to what failed in OnOpenDocument
    TRACE0("CDocument::OnOpenDocument returned FALSE.\n");
    pFrame->DestroyWindow();
    return NULL;
    }
    pDocument->SetPathName(lpszPathName);
    */
    }

    InitialUpdateFrame(pFrame, pDocument, bMakeVisible);
    return pDocument;
    }注意创建文档对像后, pDocument->m_bAutoDelete一定要设置为FALSE, 因为我们是多子框架窗口都要使用同一个文档对象。在文档模板类的析构函数, delete这个唯一的Doc对象
    CMDISingleDocTemplate::~CMDISingleDocTemplate()
    {
    if (m_pOnlyDoc != NULL)
    delete m_pOnlyDoc;
    }另外我屏蔽了OnOpenDocument调用, 因为仅使用一个doc对象, 自然程序中要对新建操作做特殊处理。这种方法可以很方便的实现单一文档--多子框架-多视图的应用。 还可以扩展为多文档模板公用同一个文档对象。