简体   繁体   English

Windows窗体组件访问

[英]Windows Form Components Access

What is the best way to access components (eg imagelist, timer) from a form instance? 从表单实例访问组件(例如,图像列表,计时器)的最佳方法是什么? I am working on multi form windows forms application on .NET Compact Framework version 3.5 SP1 with C#. 我正在使用C#在.NET Compact Framework 3.5 SP1上的多窗体Windows窗体应用程序上工作。 I have a Controller class associated with each form for MVC implementation. 我有一个与每个窗体相关联的Controller类,用于MVC实现。 Here is my sample Controller class. 这是我的示例Controller类。

public class Controller
{
      public void Init(Form f)
      {
            //f.Controls will allow access to all controls
            //How shall I access imagelist, timer on form f.
      }
}

My question is how can I access non visual components without taking a performance hit of reflection? 我的问题是,如何在不影响反射性能的情况下访问非可视组件? Any code snippets are welcome. 欢迎使用任何代码段。 If reflection is only way, then can you provide me optimal way for components access please? 如果仅是反射,那么您能为我提供组件访问的最佳方法吗?

Thanks, 谢谢,

您应该传递一个强类型的窗体或接口实现,该实现要么直接公开控件(而不是首选),要么将视图上的操作抽象为可以从控制器调用的方法/属性(首选)。

No, reflection is not the way. 不,反思不是办法。 In terms of simply accomplishing what you're going for, you can expose a read-only property that returns the control. 就简单地完成目标操作而言,您可以公开一个只读属性,该属性返回控件。 For example, say you have an ImageList named imageList1 on your form: 例如,假设您在表单上有一个名为imageList1ImageList

public ImageList ImageList
{
    get { return imageList1; }
}

You can then access the ImageList property to get a reference to imageList1 . 然后,您可以访问ImageList属性以获取对imageList1的引用。

HOWEVER 然而

This is smelly code. 这是臭代码。 What you should expose is properties and functions that relate to what you need to DO with the ImageList . 应该公开的是与ImageList要做的事情有关的属性和函数。 Your external code should not care about the particular implementation on your form (in other words, it should know you need to do something with images and provide functions to accomplish those actions; it shouldn't need to know that it's an ImageList control). 您的外部代码不应该关心表单上的特定实现(换句话说,它应该知道您需要对图像做一些事情并提供完成这些操作的功能;它不需要知道它是一个ImageList控件)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM