Wednesday, April 13, 2011

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

Hello all,

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

From stackoverflow
  • 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>
    
    Joachim Kerschbaumer : well, the ItemTemplate property of an ItemsControl IS a datatemplate. if you provide some code/markup it would be much easier to help you. just stating you get an error won't help ;)
  • I think the problem is that you should x:Key properties in your resources instead of the x:Name..

    Change that, and it will work like a charm :)

  • Do you have the following tags in your Window class?

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    
    Arcturus : Hmm if it still does not work.. can you perhaps post your whole xaml file?
  • you provided the following code:

     <DataTemplate x:Key="dtExample">
            <ListBox.ItemTemplate>
            // styles go here...
            </ListBox.ItemTemplate>
        </DataTemplate>
    

    but this will not work. you cannot provide <ListBox.ItemTemplate> directly within your template. you don't need this here. just create a simple datatemplate and it should work.

  • I know that the post is too old to be interesting for the author, yet i may be interesting for those who have the same problem and google it. As I may see the problem is you should use ListBox.ItemTemplate inside ListBox. For instance, ...

0 comments:

Post a Comment