WPF – ContentProperty, it’s that simple

So there I am, creating a custom control called “RequiredLabel” that
interestingly enough is a label that has a cool icon in it to show that
whatever it is being used for is required. The control has two
properties, Text that is the text of the label and Style that is the
style of the label. Both are registered as dependency properties so
that they can be set in the xaml. I suppose it would have been fine to
simply leave good enough as good enough but I wanted it so that in the
xaml you can put the text for the label between the start and end tag
for required label. It is simply expected behavior the the content of
your control can be put in that way.

After much soul searching (i.e. Googling) I still couldn’t find the
answer. How do I make one of my dependency properties the content that
is between the tags? Well, thankfully I had an epiphany and remembered
that somewhere deep in one of my WPF books the answer was held. It is
as simple as putting the attribute above the class declaration with the
dependency property name.

public partial class RequiredLabel : UserControl
    //see full code below

This makes it so that when I use my custom control it will look like:

<customControls:RequiredLabel x:Name="lblType" Style="{StaticResource LabelGradient}">
    Defendant's Name:

It also makes it so that if I decide to extend the content to support
user controls instead of just text really easy since I can switch out
the TextBlock that makes up the user control to a panel.

Also if you want to get a glimmer of using dependency properties see
attached code.



Previous Post

Comments (3)

  1. Cheers Brian, was wondering what this was for.

  2. Very useful indeed. Thank you very much.
    Have a nice day.

  3. Artiom

    Thanks Brian, helped me a lot

Leave a Reply

Your email address will not be published. Required fields are marked *