Reputation:
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
Upvotes: 2
Views: 6169
Reputation: 1
the subject is old but here is the solution:
<Window.Resources>
<Style x:Key="ListBoxItem_Color" TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
*//style*
</Setter>
</Style>
</Window.resources>
<ListBox x:Name="MyListBox"
...
ItemContainerStyle="{StaticResource ListBoxItem_Color}">
<.../>
</ListBox>
Upvotes: 0
Reputation: 1313
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, <ListBox ...><ListBox.ItemTemplate> ... </ListBox.ItemTemplate></ListBox>
Upvotes: 1
Reputation: 9881
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.
Upvotes: 2
Reputation: 27065
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"
Upvotes: 0
Reputation: 27065
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 :)
Upvotes: 0
Reputation: 9881
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>
Upvotes: 5