Sunday, 29 June 2008

ContentPresenter in Items Controls

This frustrated me a little today.  In Silverlight 2 Beta 2, if you attempt to use a ContentPresenter within an ItemsControl your application hangs indefinately.

       <ItemsControl x:Name="myItems">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <ContentPresenter Content="Hello World"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

A little frustrating, in the mean time the solution is to use a ContentControl instead, the code would now look like

       <ItemsControl x:Name="myItems">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <ContentControl Content="Hello World"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

Hopefully by posting this I might remember this in the future :(

1 comment:

Daniel said...

I've experienced the same problem (and frustration!). From the MSDN documentation (http://msdn.microsoft.com/en-us/library/system.windows.controls.contentpresenter.aspx): "The ContentPresenter is responsible for the UI generation. For example, when you apply a DataTemplate to an ItemsControl such as a ListBox, behind the scenes it is actually the ContentPresenter within the ListBoxItem that creates the UI of each item."

This seems to suggest that your first, non-working example is recursively generating ContentPresentors. This is exactly the behavior I noticed in my application. Like your second example, when I replace the ContentPresentor with a ContentControl, the problem is corrected.