MFC 将数据从 CViewTree 传递到 CFormView
MFC pass data from CViewTree to CFormView
我有一个基于 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;
}
相关文章:
- Visual Studio MFC C++ "CFormView" "base class"下拉列表中缺少
- C++无法在对话框 CFormView 中显示 ActiveX 控件,则控件变量为 NULL
- MFC 将数据从 CViewTree 传递到 CFormView
- 初始化 MFC 中 CFormView 派生类的成员数据
- 如何在 MDI MFC C++ Windows 应用程序中动态更改 CFormView 宽度或高度?
- 如何在 MFC[CFormView] 中创建 3D 文本
- 如何在MFC SDI CFormView应用程序中调整窗体(对话框)的大小
- MFC强制CMultiDocTemplate中的CFormView始终处于顶部
- 将 CView 转换为 CFormView
- CFormView(MFC)中的父窗口为NULL