在类向导中为控件添加相应的变量时,classwizard会为控件和变量建立一个相应的关联,下面以EditBox为例来说明:
选中Edit Control控件,鼠标右击,选择添加变量,选择变量类型为value,输入变量名称,权限为private,点击确定按钮。
上述操作的过程也可由开发者手动打入代码中,在代码中反映如下:
类的头文件:
private: CString strFilePath;
类的实现文件:
void XxxDlg::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); DDX_Text(pDX, IDC_FILEPATH_EDIT, strFilePath); }
注:上面的DoDataExchange 函数其实是为了实现一项数据动态绑定技术,DDX_XXX函数才是真正实现动态绑定技术的函数,该函数在MFC\Include\AFXDD_.H中声明。
此时即可在需要用的函数中使用UpdateData函数,其中
Updatedata(TRUE) 表示将控件的值赋值给成员变量,即从窗口编辑框中读入数据;
Updatedata(FALSE) 表示将成员变量的值赋值给控件,将数据从窗口显示。
举例:
给类添加俩个映射函数,其中OnBnClickedReferenceButton()为点击参照按钮对应的函数,OnEnChangeFilepathEdit()为编辑框内容变化即被调用的函数。
BEGIN_MESSAGE_MAP(PrnFileChooseDlg, CPropertyPage) ON_EN_CHANGE(IDC_FILEPATH_EDIT, &PrnFileChooseDlg::OnEnChangeFilepathEdit) ON_BN_CLICKED(IDC_REFERENCE_BUTTON, &PrnFileChooseDlg::OnBnClickedReferenceButton) END_MESSAGE_MAP()
void XxxDlg::OnEnChangeFilepathEdit() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CPropertyPage::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here UpdateData(TRUE);//用户在编辑框中一边输入数据,UI上的数据内容一边赋给绑定的变量。 setNextBtnStatus(); } //Click the reference button to choose the expected file. void XxxDlg::OnBnClickedReferenceButton() { // TODO: Add your control notification handler code here choosePrnFile(); }
void XxxDlg::choosePrnFile() { CFileDialog dlgFile(TRUE, NULL, NULL, OFN_HIDEREADONLY, _T("Describe Files (*.prn)|*.prn|All Files (*.*)|*.*||"), NULL); if (dlgFile.DoModal()) { strFilePath = dlgFile.GetPathName(); setNextBtnStatus(); } UpdateData(FALSE);//用户点击参照按钮选好文件地址后,赋给绑定的变量strFilePath,然后反映到对应的编辑框中。 }
//Set the status of the next button. void XxxDlg::setNextBtnStatus() { pWnd = tmpSheet->GetDlgItem(ID_WIZNEXT); if(strFilePath == _T("")) { pWnd->EnableWindow(FALSE); } else { pWnd->EnableWindow(TRUE); } }
头文件如下:
class XxxDlg: public CPropertyPage { DECLARE_DYNAMIC(PrnFileChooseDlg) public: XxxDlg(); virtual ~XxxDlg(); virtual BOOL OnSetActive(); virtual LRESULT OnWizardBack(); virtual LRESULT OnWizardNext(); // Dialog Data enum { IDD = IDD_PRNFILECHOOSE_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: afx_msg void OnEnChangeFilepathEdit(); afx_msg void OnBnClickedReferenceButton(); virtual BOOL OnInitDialog(); private: void setNextBtnStatus(); void initializeWizardBtns(); void choosePrnFile(); private: CString strFilePath; CPropertySheet *tmpSheet; CWnd *pWnd; };
