No Free Time

Because my therapist says I need to let things out

Silverlight 2: How to put a user control inside a DataTemplate

Posted by andrewmyhre on March 30, 2008

Note: this post is quite old and probably doesn’t apply to the latest Silverlight 2 release.

I have a Silverlight user control with the following XAML:

<UserControl x:Class=”Continuator.SimpleControl”
xmlns=”http://schemas.microsoft.com/client/2007″
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Width=”400″ Height=”300″>
<Grid x:Name=”LayoutRoot” Background=”White”>
<TextBlock Text=”hello” />
</Grid></UserControl>I want to use it in a ListBox/StackPanel data template. To do so I first add a reference from my Page.xaml:

<UserControl x:Class=”Continuator.Page”
xmlns=http://schemas.microsoft.com/client/2007
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:c=”clr-namespace:Continuator;assembly=Continuator”
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns
:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″ mc:Ignorable=”d”
Width=”800″ Height=”600″>

(My project namespace is called Continuator). The specifying the assembly is crucial – this won’t work without it and in my case actually caused a bad memory leak. Now add your ListBox to the page, with the control specified in the data template:

<ListBox x:Name=”ProjectsList”>
<ListBox.ItemTemplate>
<DataTemplate>
<c:SimpleControl />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
If you’ve tried this and have had problems, check that you’re including the assembly in the namespace reference. I found this tip in this thread.

One Response to “Silverlight 2: How to put a user control inside a DataTemplate”

  1. Assaf said

    Thank you, you saved me a lot of time!

    I had the same problem and fixed it by changing the assembly name to match to root namesapace name

    Assaf

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>