无法访问类中的 Winforms 控件 [英] Unable to access Winforms control in a class

查看:35
本文介绍了无法访问类中的 Winforms 控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 Visual Studio 2008 在 C# 中处理一个小型 Windows 窗体项目.我在项目中添加了一个自定义类,但在这个类中,我无法访问表单控件(如列表框、文本框、按钮)以通过编程方式更改它们的属性.

I am currently working in a small windows forms project in C# using Visual studio 2008. I have added a custom class to the project, but in this class I am unable to access the forms controls (like listbox, textbox, buttons ) in order to programmatically change their properties.

类文件包含 using system.windows.forms 并且所有文件都在同一个命名空间中.令人惊讶的是,我也无法访问form1类本身中的控件,除非我在类中创建了一个方法然后intellisense弹出各种控件的名称.

The class file has using system.windows.forms included and all files are in the same namespace. Surprisingly, I am also unable to access the controls in the form1 class itself, unless I create a method in the class and then intellisense pops up the names of the various controls.

然而,在自定义类中,intellisense 根本不显示控件的名称.

in the custom class however, intellisense does not show the names of the controls at all.

感谢有人能解释为什么会发生这种情况.

Appreciate if someone coudl shed some light on why this could be happening.

谢谢

推荐答案

封装意味着您的独立类不应该直接与控件对话.相反,您应该在(外部)Control 上公开属性和方法 - 例如:

Encapsulation means your separate class shouldn't be talking directly to the controls. You should, instead, expose properties and methods on your (outer) Control - for example:

public string TitleText {
    get {return titleLbl.Text;}
    set {titleLbl.Text = value;}
}

对于更复杂的操作,最好使用一种方法;属性适用于对谨慎值的简单读/写.

For more complex operations it may be preferable to use a method; properties are fine for simple read/write for discreet values.

这提供了各种优势:

  • 如果需要,您可以将详细信息抽象为接口(或类似接口)
  • 您可以在不更改调用代码的情况下更改实现(例如,使用表单的文本作为标题)
  • 它只是......更好;-p

这篇关于无法访问类中的 Winforms 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆