采用 MFC 编制 MVC 模式之球体演示程序
2006-07-19 11:30:56 来源:WEB开发网核心提示: class CSphere{public: ... ....//更新Graphic-VIEWBOOL UpdateGraphicView(HWND hWnd,const CRect &rect,BOOL bErase);//更新Text-VIEWvoid UpdateTextView();
class CSphere
{
public:
... ....
//更新Graphic-VIEW
BOOL UpdateGraphicView(HWND hWnd,const CRect &rect,BOOL bErase);
//更新Text-VIEW
void UpdateTextView();
//外界Controller的接口:设置球体半径
void SetRadius(float r);
private:
//球体半径
float m_fRadius;
//计算球体表面积
float CalculateArea(float radius);
//计算球体体积
float CSphere::CalculateVolumn(float radius);
};
这里面 UpdateTextView,UpdateTextView 就是当用户输入新半径或拖动鼠标 Controller 捕获后通知 Model,Model 通知两个View更新显示 。具体代码如下:
BOOL CSphere::UpdateGraphicView(HWND hWnd,const CRect &rect,BOOL bErase)
{
//data format examination
if(!::IsWindow(hWnd)||::IsRectEmpty(&rect))
{
AfxMessageBox("View is not created by now or rect is empty");
return false;
}
//get the window pointer from window handle
CWnd *pView = CWnd::FromHandle(hWnd);
if(pView == NULL)
return false;
//set graphic view''s radius in order to painting
((CGraphicView*)pView)->SetRadius(m_fRadius);
bPaintSphere = true;//set paint tag true
//repaint
if(!::InvalidateRect(hWnd,&rect,bErase)&&
!::UpdateWindow(hWnd))
{
AfxMessageBox("UpdateView failed");
return true;
}
pView = NULL;
return false;
}
void CSphere::UpdateTextView()
{
CMVCSphereDlg *parent = (CMVCSphereDlg *)AfxGetMainWnd();
CWnd *wnd1 = parent->GetDlgItem(IDC_SURFACE);
CWnd *wnd2 = parent->GetDlgItem(IDC_VOLUMN);
CString str;
str.Format("%.2f平方米",CalculateArea(m_fRadius));
wnd1->SetWindowText(str);
str.Empty();
str.Format("%.2f立方米",CalculateVolumn(m_fRadius));
wnd2->SetWindowText(str);
}
CGraphicView中绘图关键代码如下:
更多精彩
赞助商链接