65.9K
CodeProject is changing. Read more.
Home

Embedding Content inside a UserControl from its Parent Control in Silverlight 4

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Oct 7, 2010

CPOL
viewsIcon

18107

How to embed Content for a UserControl when consumed by another control using ContentProperty

Introduction

Whenever you create your own UserControl in Silverlight, it bothered me that when consuming the usercontrol in a parent control (e.g., the page), it is not allowed to access the user control's content.
Example: assume the following code as part of a consumer control:

<Grid x:Name="LayoutRoot">
  <MyApp:MyUserControl>
    <TextBlock Text="This is consumer defined content!"></TextBlock>
  </MyApp:MyUserControl>
</Grid>

You get the following error: "The property 'Content' does not exist on the type....".

The problem is that the Content property is a private property of the UserControl.
However, there is a workaround for this problem: the ContentProperty attribute.

Here are the steps to follow:

  1. In your UserControl.xaml, add a ContentPresenter control that will hold the user defined content. Name the ContentPresenter 'contentPresenter'.
  2. In your UserControl codebehind, define a new property:
    public object UserContent
    {
        get { return contentPresenter.Content; }
        set { contentPresenter.Content = value; }
    }
  3. Now for the trick: add the following attribute to the class:
    [ContentProperty("UserContent")]<br />

There, that's it! You can now create your layout within the UserControl XAML and embed the actual user content at any position within your user control.

History

  • 7th October, 2010: Initial version