locked
How to encapsulate custom content in a userControl? RRS feed

  • Question

  • Hello,

    I need to have a usercontrol which can hold additional content assigned to it from the silverlight page it's contained.

    So if I have this page:

    <LayoutRoot>
       <myUserControl>
          <TextBlock Content="Hello World!"/>
       </myUserControl>
    </LayoutRoot>

    What do I need in the xaml of my UserControl to get this to work?
    I allready know how to do this with creating a control from a template like the button, but I need a usercontrol which has a codebehind file as well.

    Please help :)

    Greetings,

    SonicTTH

    Tuesday, February 1, 2011 7:25 AM

All replies

  • You will probably want to use a class derived from ContentControl:

    http://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol%28v=VS.95%29.aspx

    If you search for ContentControl silverlight you will find some good references on how to do this. This will give you an object with a content property, a code behind, and xaml code (generally as a template).

    Tuesday, February 1, 2011 3:32 PM
    Moderator
  • A custom control is probably the best way, but it is quit complicated: You have to write your custom class and create a standard design in generic.xaml. When you have a lot of references to XAML-Elements, than a better and easier way can be an extended user-control. Just add your own properties as dependency properties in the code-behind file. If you want to add custom content to each representation of your user-control, add a dependency property of type “object”, mark is as content property like this: [ContentProperty(“MyPropertyName”)]. Then add a content presenter in your user-control and bind the content property with element binding your own property on the root element. Now use your user-control and just drop another control on it in Expression Blend.
    Sunday, February 6, 2011 3:16 PM