从其他类访问对话框控件变量 [英] Accessing Dialog Control variables from other classes
问题描述
我正在使用VS2008,并且我有一个MFC对话框应用程序,其中包含一个按钮和一个列表控件.列表控件具有一个控制变量m_listctrl. m_listctrl变量在dialog.h的公共部分中声明.
当我单击按钮时,我在另一个类中调用一个函数.从该函数中,我需要访问m_listctrl变量,以便可以基于我所在的类中其他函数中的数据来修改列表控件的内容.
如果我在这样的类中插入一行:
m_ListCtrl.InsertItem(0, _T("TESTING"))
我收到一个编译错误,指出m_ListCtrl是未声明的标识符.在我的班级文件中,我#defined了dialog.h.我没有运气就尝试了多种解决方法.
我意识到仅通过在CDialog类中工作就可以避免所有这些情况.但是该代码已经超过800行.我只是想将代码分解为较小的部分.
从CDialog类外部访问控制变量的正确方法是什么?
I am using VS2008 and I have a MFC Dialog application that contains a button and a List Control. The List Control has a control variable m_listctrl. The m_listctrl variable is declared in the public section of dialog.h.
When I click the button I call a function in another class. From within that function I need to access the m_listctrl variable so I can modify the contents of the List Control based on data in other functions within the class I am in.
If I insert a line in the class like this:
m_ListCtrl.InsertItem(0, _T("TESTING"))
I get a compile error stating the m_ListCtrl is an undeclared identifier. In my class file I have #defined the dialog.h. I have tried multiple work arounds with no luck.
I realize I could avoid all this by just working in the CDialog class. But that code is already over 800 lines long. I am just trying to break the code down into smaller pieces.
What is the proper way to access the control variable from outside the CDialog class?
推荐答案
您还需要引用该CDialog
对象,因为m_ListCtrl
是在那里有一个声明的标识符,还有实例化的对象.
如果您认为编译器不可能在任何时候得到一个以上的CDialog
对象,那么您就不可能猜测到哪个m_ListCtrl
是很合逻辑的.因此需要引用特定的CDialog
对象.
应该是这样的:
You would also need the reference to thatCDialog
object becausem_ListCtrl
is a declared identifier, and also instantiated object, there.
This is also quite logical if you consider that it would be impossible for the compiler to guess whichm_ListCtrl
you mean if at any time you got more than one object ofCDialog
. The reference to the specificCDialog
object is therefor required.
It should be something like:
m_CDialog.m_ListCtrl.InsertItem(0, _T("TESTING"))
顺便说一句,提供一种从对话框本身添加值的方法会更加安全.这意味着您将创建一个CDialog.AddListItem(...)
.如果直接公开m_ListCtrl
,则其他代码可以完全操纵此控件.使用您自己的方法从CDialog
中公开,您可以防止此情况发生,并且外部代码只能添加一个值,而不能删除项目,更改字体或对列表控件进行任何其他不需要的更改.
祝你好运!
By the way, it would be much more safe to provide a method for adding a value from the dialog itself. This means you would create a CDialog.AddListItem(...)
. If you expose m_ListCtrl
directly, other code can manipulate this control completely. With the your own method exposed from CDialog
you prevent this and external code can only add a value, but not delete items, change the font or make any other unwanted changes to the list control.
Good luck!
这篇关于从其他类访问对话框控件变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!