Search code examples
c#wpfxamlitemtemplate

How do I embed the ItemTemplate for a wpf ListBox into the Window's resources?


Sorry if this is a basic question, but how can I take an ItemTemplate that I have for a ListBox, and put it in the resources for the window so that more than one ListBox can use it.

Here's some XAML:

<Window x:Class="Example">
    <Window.Resources>
        <DataTemplate x:Key="dtExample">
            <ListBox.ItemTemplate>
            // styles go here...
            </ListBox.ItemTemplate>
        </DataTemplate>
    </Window.Resources>
    <ListBox ItemTemplate="{StaticResource dtExample}">
    // items go here...
    </ListBox>
</Window>

This is throwing a "Attached property has no setter" design-time error. I've removed portions of code that I didn't think would matter, for sake of brevity.

Thanks


Solution

  • just add your itemtemplate to your window's resource and add a key:

    <Window.Resource>
     <DataTemplate x:Key="myTemplate">
      ....
     </DataTemplate>
    </Window.Resources>
    

    and then apply it with something like this:

    <ListBox ItemTemplate="{StaticResource myTemplate}">
     ...
    </ListBox>