accessing Winform`s private UI Component into another class in C#
I have WinForm which is a tab based and including all Tabs it has around 60 UI Components. Depending upon value selected in some UI Components i am Auto filling rest of the UI components.For this i would like to write a helper class.But the problem is if i pass Winform object to that class i am not able to access values on that Form because all开发者_开发知识库 the member are declared private.
one possible solution is that I can write around 60 properties in the Winform but i think this is not the best way to do it. I would like to know what is the best way to handle problem like these ?
You could change the Modifiers for your UI components from private
to internal
. This would allow all classes within the same project to directly access the components.
However, I would argue that exposing the necessary components through properties is a better design than exposing them publically/internally. I acknowledge that it includes a fair amount of typing, but it's safer as you can expose them cleanly, in a manner specific to your use case.
That being said - there are a couple of things I would consider:
- Can this be refactored into a smaller class, using fewer components by using UserControls? This might make it more managable, as well as promote reuse. 60 UI elements is a fair amount for a single screen.
- Can you refactor this to pass the data, instead of trying to work with the controls directly? For example, you could auto-fill the data via a shared interface, and data bind the controls to the data, or something similar.
You can declare the members of a WinForm as public protected, protected internal, and internal. You can do this either in the properties window for a specific component (go to the Modifiers property) or you can change them in the Designer of the form (they are declared after the "Windows Form Designer generated code").
If you don't want to make the members public, nor make a property or method to get that information, then all you're left with is attempting to get the value via reflection, which is perhaps the worst option of all three.
Your best solution would be to make properties for each of those private members and expose them that way.
One way to approach this is to create a class that contains all of the data that you want to bind to (e.g. a class that implements INotifyPropertyChanged).
Then share this instance between the WinForm and the other class. Voila!
精彩评论