I’m designing a UI manager class that will manage all my UI elements (this is for an XNA game, so there is no existing UI framework) but I’m wondering how to deal with situations where I want the UI manager to have special access to data in the UI elements that other classes can’t access.
For example, I want to have a SetFocus method to focus a specific element and this method needs to ensure that the previously focused element loses focus. The individual UI elements themselves can’t handle this because they don’t have access to the list of UI elements, which means the manager has to handle it, but how can I allow the manager and only the manager to set the variable on a UI element?
The thought occurs to me to just store the currently focused element on the manager, however I don’t particularly like that solution and, given a single UI element, I would like to query it to find out if it has focus. Even if it makes sense to store the currently focused element on the manager since its just a single variable, there are other things I need to deal with that would require arrays to associate the data with the elements if its stored on the manager, and that just seems to defeat the purpose of OOP.
I know I don’t need to have it so that the manager is the only one with access to this data, I could just make all the data public, but that’s not good design…
What you are looking for is a C# equivalent of the C++ friend concept. As you read in the linked post ‘the closest that’s available (and it isn’t very close) is InternalsVisibleTo‘ (citing Jon Skeet). But using
InternalsVisibleToin order to accomplish what you want would mean you’d have to break up your complete application into a library per class, which would probably create a DLL hell.Building upon MattDavey’s example got me:
Whether a
Controlhas focus is now only stored in theManagerand only theManagercan change the focusedControl.A little example how to put things together, for completeness: