I have a ChildUserControl that is loaded inside a ParentUserControl. The host page loads ParentUserControl.
I would need to access properties in ParentUserControl from the ChildUserControl.
Thanks for your time
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The platform / language etc isn’t clear, so this answer is necessarily vague… however, in general a child control can’t access properties from the parent (directly), because lots of different types of parent controls could be hosting the child control. The child shouldn’t be hard-coded to a single parent, otherwise it might as well be part of the parent.
Generally, you might want to try to simply remove the requirement – it sounds like an odd design. However, some frameworks support something like this – for example, dependency properties in WPF.
An interface-based design (for the parent(s)) is one approach, but this isn’t very clean. For .NET, events etc are another common way for a child to communicate with a parent – the child exposes events which different parents can consume in different ways.
Other than that, you’re into the territory of testing/casting the parent (either against a class or an interface) to access details from the parent – for example:
(could also use an interface here; still a bit hacky either way…)
Personally, rather than use this type of cast from the child, I’d prefer the parent to take control; the parent sets properties on the child, and listens to events (rather than the child set properties back on the parent):
This way, the child doesn’t know or care about the parent. All it knows is that it has properties (etc), and can notify other people to interesting changes.