MFC Dialog Data Exchange

17 December, 2008 § 1 Comment

I’ve been surprised to learn that there are developers who have worked in MFC for a long time and never really knew much about Dialog Data Exchange. I don’t fault them, since the easiest way to stumble upon it is through the Forms Designer’s context menu (besides seeing it in the generated code and having no clue what it does).

Dialog Data Exchange (DDX) is a really nifty feature that MFC brought forward to use when working with user interfaces. DDX strongly types variables and controls in the Dialog/Form’s associated class to the objects found in the UI.

This means you can get rid of GetDlgItem. Why does this help? Besides removing code and tons of enums interspersed throughout your code, it allows the ability to subclass a control easily with minimal code changes. Here is a short example:

void CMyDialog::GetTitle()
{
   CEdit* pTitle = ( (CEdit*) GetDlgItem( IDC_TITLE_EDIT ));
   CString strTitle;
   pTitle->GetWindowText( strTitle );
   return strTitle;
}

Imagine seeing similar functions littered all over your code. This might have happened immediately or through maintenance. All is fine though, it all works and it gets the job done. But just today your UX lead decided that all the controls be custom-drawn and implement some special behaviors. To solve this, you subclass all of your controls, but to finish the work, you've got to go through and fix all the of the type casts, which is easy to forget considering that the cast in place is perfectly valid.

With DDX, all you have to do is change your definition in your header file and your work is done. This is what your code will look like afterwards:

void CMyDialog::GetTitle()
{
   CString strTitle;
   m_cTitle.GetWindowText( strTitle );
   return strTitle;
}

That's one less line of code for each of these methods. You can also tie non-control variables to the controls in the form. If you have a CEdit control, you can have a CString tied to it so when the dialog returns from DoModal, the public CString variable will hold the value of the CEdit. Validation, min-max values and other options can also be set with DDX and DDV (Dialog Data Validation).

MSDN has more information on the specific DDX and DDV routines and Joseph Newcomer's essay on Avoiding GetDlgItem.

Tagged: , , , ,

§ One Response to MFC Dialog Data Exchange

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading MFC Dialog Data Exchange at JAWS.

meta

Follow

Get every new post delivered to your Inbox.

Join 1,004 other followers