MFC Dialog Data Exchange

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:

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:

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).