问题
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
回答1:
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>
回答2:
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.
回答3:
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>
回答4:
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 :)
回答5:
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"
来源:https://stackoverflow.com/questions/641815/how-do-i-embed-the-itemtemplate-for-a-wpf-listbox-into-the-windows-resources