DDX_Control mfc 示例

DDX_Control example for mfc

我无法获得 DDX_Control 工作示例。

创建对话框时,无法为控件对象创建引用。

Google 也没有例子。

谢谢。

void CEditDialog::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_COMBO1, m_cmbBox);
    DDX_Text(pDX, IDC_EDIT1, m_Edit);
}

void CMFCApplicationDDEView::OnActionEdit2()
{
    // TODO: Add your command handler code here
    CEditDialog dlg;
    CString str;
    dlg.m_cmbBox.GetLBText(0, str);

    if (dlg.DoModal() == IDOK)
    {
        MessageBox(dlg.cmbItemStr);
    }
}

dlg.m_cmbBox 为 NULL。为什么它为 null 以及如何在我的视图中引用它

您的组合框和对话框代码是正确的,但是m_cmbBox.GetLBText()不能在DoModal()前后使用,因为没有window句柄。覆盖下面的代码,然后访问 combo_str 而不是访问 windows

BEGIN_MESSAGE_MAP(CEditDialog, CDialog)
    ON_COMMAND(IDOK, OnOK)
    //...
END_MESSAGE_MAP()

BOOL CEditDialog::OnInitDialog()
{
    BOOL res = CDialog::OnInitDialog();
    //Dialog is created, window handles are available, set text here
    return res;
}

void CEditDialog::OnOK()
{
    //get text before dialog's window handles are destroyed
    int sel = m_cmbBox.GetCurSel();
    if (sel >= 0) m_cmbBox.GetLBText(sel, cmbItemStr);
    CDialog::OnOK();    
}

@barmak 在 InitDialog() 执行之前不能直接访问对话框控件是正确的。

但是,您可以使用 DDX_CBString 设置/检索组合框编辑部分的文本,例如:

// in .h file
CString m_cmbItemStr;

// in .cpp
void CEditDialog::DoDataExchange(CDataExchange* pDX)
{   CDialog::DoDataExchange(pDX);
    DDX_CBString(pDX, IDC_COMBO1, m_cmbItemStr);
    DDX_Text(pDX, IDC_EDIT1, m_Edit);
}

void CMFCApplicationDDEView::OnActionEdit2()
{   CEditDialog dlg;
    CString str = TEXT("some value");
    dlg.m_cmbItemStr = str;

    if (dlg.DoModal() == IDOK)
        MessageBox(dlg.m_cmbItemStr);
}