如何将用于wpf ListBox的ItemTemplate嵌入到Window的资源中?

2 c# wpf xaml itemtemplate

很抱歉,如果这是一个基本问题,但我如何获取ListBox的ItemTemplate,并将其放在窗口的资源中,以便多个ListBox可以使用它.

这是一些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>
Run Code Online (Sandbox Code Playgroud)

这是一个"附加属性没有设置者"设计时错误.为了简洁起见,我删除了一些我认为不重要的代码.

谢谢

Joa*_*mer 5

只需将您的itemtemplate添加到窗口的资源并添加一个键:

<Window.Resource>
 <DataTemplate x:Key="myTemplate">
  ....
 </DataTemplate>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

然后用这样的东西应用它:

<ListBox ItemTemplate="{StaticResource myTemplate}">
 ...
</ListBox>
Run Code Online (Sandbox Code Playgroud)