Failed to access Winforms control in class.

I am currently working in a small Windows Forms project in C # using Visual Studio 2008. I added my own class to the project, but in this class I cannot access form controls (for example, listbox, textbox, buttons) so that programmatically change their properties.

The class file uses the system.windows.forms file, and all the files are in the same namespace. Surprisingly, I also can’t access the controls in the form1 class itself, unless I create a method in the class and then intellisense displays the names of the various controls.

in a custom class, however intellisense does not display control names at all.

Appreciate if someone coudl sheds light on why this might happen.

thanks

+3
source share
4 answers

Encapsulation means that your individual class should not talk directly to controls. Instead, you should show properties and methods on your (external) 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 great for simple read / write for hidden values.

This provides various benefits:

  • You can, if necessary, abstract the details to an interface (or similar).
  • you can change the implementation (for example, use the form text for the name) without changing the call code
  • it's just ... better ;-p
+4

. , , .

, , . .

, , 100% , , , . .

, , , .

+3

Form1

partial class Form1
{
   //elided other good stuff 
   private System.Windows.Forms.Button button1;
}

, .

, @abatishchev ( ). @Marc Gravell. , , ( @Rune Grimstad). , . . . , , , , , .

+3
source

See how this can be implemented using the MVP template (sample code): Implementing MVC with Windows Forms

UPDATE: the code in the class you specify should actually be part of the form presenter, which has a link to the form (via the IView interface). This is how you should design your user interface code, and not directly access other parts of the form.

0
source

Source: https://habr.com/ru/post/1706096/


All Articles