I have a custom UserControl in Silverlight which in all simplicity is composed of TextBlocks and TextBoxes. I have a hierarchy of class entities as follows:
- Person is an abstract super class that contains the properties Name and Age
- Man is a child of Person that adds the property FacialFeature
- Woman is a child of Person that adds the property LastMenstruated and HasHymen
So:
- a Person contains the properties Name and Age
- a Man contains the properties Name, Age and FacialFeature
- a Woman contains the properties Name, Age, LastMenstruated and HasHymen
What I want is for my UserControl to simply display the values of those properties like so:
if Person is of type Man:
Name : Mark
Age : 23
FacialFeature : Fully Shaved
or if Person is of type Woman:
Name : Jane
Age : 8
LastMenstruated : Never
HasHymen : Yes
Bear in mind this is a simplified example for the sake of my question.
What I want is for my UserControl to display different information and possibly display it differently depending on the run-time type of Person.
I have thought about creating the control in the code-behind using a switch statement that would switch on GetType(Person), but what I don’t like about this, is that the logic would be in the UserControl. I would like a solution that has the objects encapsulate their own display, so that if I add new types of Person, I don’t need to go back to the UserControl and add in a case for the new types, etc.
Taking your male/female split as an example you need to bind the
Visibiltyof the elements to the object being displayed through a converter that takes a parameter:Then in your converter:
This means that you don’t have to add arbitrary UI properties to your classes to get them to display how you want them to.
I’m not 100% sure of the tests for the object type (I don’t have Silverlight 5 installed on this machine)
More information on the
IValueConverterinterface can be found on the MSDN.