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.

[ContentProperty("Text")]
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:
</customControls:RequiredLabel>

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.

RequiredLabel.zip

Brian

Leave a Reply

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

FormatException

928 East Plymouth Drive Asbury Park, NJ 07712