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

一笑奈何 提交于 2019-12-11 02:23:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!